用CTE订购联合结果

时间:2015-02-03 15:22:59

标签: postgresql sql-order-by common-table-expression

当我有几个CTE后跟UNION of SELECT时,如何使用ORDER BY。我的查询是这样的:

WITH
cte1 AS (SELECT * FROM table1),
cte2 AS (SELECT * FROM table2),
cte3 AS (SELECT * FROM table3)
SELECT cte1.column1,cte1.column2 FROM cte1
UNION
SELECT cte2.column1,cte2.column2 FROM cte2
UNION
SELECT cte3.column1,cte3.column2 FROM cte3

我需要按column1对结果进行排序,其中所有CTE都是整数。

1 个答案:

答案 0 :(得分:1)

只需添加order by

即可
WITH cte1 AS (SELECT * FROM table1),
cte2 AS (SELECT * FROM table2),
cte3 AS (SELECT * FROM table3)
SELECT cte1.column1,cte1.column2 FROM cte1
UNION
SELECT cte2.column1,cte2.column2 FROM cte2
UNION
SELECT cte3.column1,cte3.column2 FROM cte3
order by column1 --<< here

联盟上的order by总是命令完整联合,而不仅仅是最后一次选择。


顺便说一句:您可能还想了解unionunion all之间的区别。如果您知道在个人选择(或不关心)之间没有重复,union all会更快。