在带有UNION子句的postgres中使用ORDER BY的问题

时间:2019-04-26 00:27:11

标签: sql database postgresql

我正在尝试在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"

但是我遇到了这个错误

missing FROM-clause entry for table "users"
LINE 10: 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"
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"

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

不使用表别名,而仅通过表别名来引用列:

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";

SELECT DISTINCT是多余的,因为UNION会删除重复项。