使用 CTE 排序并集结果

ordering union results with CTEs

当我有几个 CTE 后跟 SELECT 的 UNION 时,如何使用 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 中都是一个整数。

只需添加一个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 总是排序完整的并集,而不仅仅是最后一个 select。


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