简体   繁体   English

MySql:保留 UNION ALL 结果中的顺序

[英]MySql: Preserving order in UNION ALL result

I have the following:我有以下内容:

with
result1 as ( select column1 from table1 order by ... )
result2 as ( select column1 from table2 order by ... )
select * from result1 union all select * from result2;

The intent is to list result1 with its order preserved followed by result2 with its order preserved .目的是列出保留顺序的result1 ,然后列出保留顺序result2 However, it appears that union all does not preserve the order of its operand tables.但是, union all似乎并没有保留其操作数表的顺序。 How can I get the intended effect?我怎样才能达到预期的效果? I have tried adding columns to the ordered result1 and result2 and then order the union result on this added column, but this seems awfully klugy for something that seems pretty typical.我已经尝试将列添加到有序的result1result2 ,然后在这个添加的列上对联合结果进行排序,但这对于看起来非常典型的东西来说似乎非常笨拙。 Is there anything like union all ordered ?有没有像union all ordered这样的东西?

Ok.行。 Here is how you sort it out with "window functions".以下是您如何使用“窗口函数”对其进行排序。 Provided you are using MySQL 8+前提是你用的是MySQL 8+

with
result1 as ( 
select column1, ROW_NUMBER() OVER (ORDER BY ...) AS rownum1, 0 AS rownum2, 
from table1 order by ...
),
result2 as ( 
select column1, 0 AS rownum1, ROW_NUMBER() OVER (ORDER BY ...) AS rownum2
from table2 order by ...
),
result as (
select * from result1 
union all
select * from result2 
)
     
select * from result order by rownum2, rownum1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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