简体   繁体   中英

problem using ORDER BY in postgres with UNION clause

I am trying to run this query in postgresql

SELECT DISTINCT users."uid", tax."tid"
FROM tax
LEFT JOIN users ON tax."uid" = users."uid"

UNION 

SELECT DISTINCT users."uid", tax."tid"
FROM tax 
LEFT JOIN users ON tax."uid" = users."uid"
ORDER BY users."uid", tax."tid"

but I come across this error

missing FROM-clause entry for table "users"
LINE 10: ORDER BY users."uid", tax."tid"

however, when I run these queries I come across no problem and the results are as expected :-

SELECT DISTINCT users."uid", tax."tid"
FROM tax 
LEFT JOIN users ON tax."uid" = users."uid"
ORDER BY users."uid", tax."tid"
SELECT DISTINCT users."uid", tax."tid"
FROM tax
LEFT JOIN users ON tax."uid" = users."uid"
ORDER BY users."uid", tax."tid"
SELECT DISTINCT users."uid", tax."tid"
FROM tax
LEFT JOIN users ON tax."uid" = users."uid"

UNION 

SELECT DISTINCT users."uid", tax."tid"
FROM tax 
LEFT JOIN users ON tax."uid" = users."uid"

what am I doing wrong here?

Leave out the table aliases and refer to the columns only by their table aliases:

SELECT users."uid", tax."tid"
FROM tax LEFT JOIN
     users
     ON tax."uid" = users."uid"
UNION 
SELECT users."uid", tax."tid"
FROM tax LEFT JOIN
     users
     ON tax."uid" = users."uid"
ORDER BY "uid", "tid";

The SELECT DISTINCT is redundant, because UNION removes duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM