"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 \"Error: The used SELECT statements have a different number of columns\" in UNION Operations?

How to Resolve \"Error: The used SELECT statements have a different number of columns\" in UNION Operations?

Published on 2024-11-10
Browse:828

How to Resolve \

Error: Discrepancies in Column Count in SELECT Statements

When executing a query involving multiple SELECT statements, such as a UNION operation, it's imperative to ensure that each statement contains exactly the same number of columns. Failure to do so will result in the "Error: The used SELECT statements have a different number of columns" error.

To resolve this issue, the query needs to be rewritten such that each SELECT clause has an identical number of columns with compatible data types. For instance, 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 

suffers from this error as the first SELECT contains 4 columns ("", u1., u2.*), while the second SELECT only returns a single column ("fid2").

A more straightforward rewrite that preserves the intended functionality is:

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 

By ensuring that both SELECT statements return the same number of columns with matching data types, the query can be executed without encountering the column count error. Additionally, it eliminates the unnecessary outer joins, which seem redundant based on the provided schema.

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