"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve the \"Disparate Column Counts in Select Statements\" Error When Using UNION?

How to Resolve the \"Disparate Column Counts in Select Statements\" Error When Using UNION?

Published on 2024-11-07
Browse:136

How to Resolve the \

Error: Disparate Column Counts in Select Statements

When executing a query that utilizes the UNION operator, it is imperative to ensure that all the individual SELECT statements involved adhere to two fundamental criteria:

  1. Matching Column Count: Each SELECT statement must yield the same number of columns in the retrieved result set.
  2. Consistent Data Types: The data types of corresponding columns across different SELECT statements should align.

Problem Analysis

Considering the provided query:

SELECT * FROM friends
LEFT JOIN users AS u1 ON users.uid = friends.fid1
LEFT JOIN users AS u2 ON users.uid = friends.fid2
WHERE (friends.fid1 = 1) AND (friends.fid2 > 1)
UNION SELECT fid2 FROM friends
WHERE (friends.fid2 = 1) AND (friends.fid1 

the error message indicates a discrepancy in column count between the two SELECT statements joined by UNION. Specifically, the first SELECT statement returns all columns from the tables involved, while the second one fetches only the fid2 column.

Solution

To resolve this issue, the second SELECT statement should be modified to match the column count of the first statement. The easiest approach is to include all the desired columns explicitly:

   SELECT f.*, u.*
     FROM FRIENDS AS f
     JOIN USERS AS u ON u.uid = f.fid2
    WHERE f.fid1 = 1 
      AND f.fid2 > 1
UNION 
   SELECT f.*, u.*
     FROM FRIENDS AS f
     JOIN USERS AS u ON u.uid = f.fid1
    WHERE f.fid2  = 1 
      AND f.fid1 

Alternatively, one could use the UNION ALL operator, which permits SELECT statements with varying column counts. However, the mismatched columns will be filled with NULL values, which may not be desirable in all cases.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3