【问题标题】:MySql: Preserving order in UNION ALL resultMySql:在 UNION ALL 结果中保留顺序
【发布时间】:2020-08-02 13:48:37
【问题描述】:

我有以下几点:

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;

目的是列出result1保留其顺序,然后是result2保留其顺序。但是,union all 似乎没有保留其操作数表的顺序。我怎样才能达到预期的效果?我尝试将列添加到已排序的 result1result2 中,然后在此添加的列上排序联合结果,但这对于看起来非常典型的东西来说似乎非常笨拙。有union all ordered之类的吗?

【问题讨论】:

  • 任何没有 ORDER BY 子句的结果集都是无序的。这同样适用于select * from result1 union all select * from result2;
  • 添加到您的 ORDER BY a LIMIT 18446744073709551615 中,这样优化器就不会删除订单
  • 选择 1 seq,table1 union 中的其他列选择 2,table 2 中的其他列...

标签: mysql sql-order-by union


【解决方案1】:

好的。这是您如何使用“窗口功能”对其进行分类的方法。前提是您使用的是 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

【讨论】:

  • 内部 ORDER BY 子句需要什么?
  • 另外:目的是列出result1并保留其顺序,然后列出result2并保留其顺序您的代码如何满足要求?
  • @forpas 我编辑了查询。排序方式,只能在最后一次选择时使用
  • 按什么排序?保留问题中描述的顺序/
  • 不,它不起作用,您可以通过阅读文档了解原因:dev.mysql.com/doc/refman/8.0/en/union.html
猜你喜欢
  • 1970-01-01
  • 2022-12-16
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
相关资源
最近更新 更多