当我有几个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都是整数。
答案 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
总是命令完整联合,而不仅仅是最后一次选择。
顺便说一句:您可能还想了解union
和union all
之间的区别。如果您知道在个人选择(或不关心)之间没有重复,union all
会更快。