mysql - MySql:在 UNION ALL 结果中保留顺序
问题描述
我有以下内容:
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
不保留其操作数表的顺序。我怎样才能达到预期的效果?我尝试将列添加到有序列,然后在这个添加的列上对联合结果进行排序result1
,result2
但这对于看起来非常典型的东西来说似乎非常笨拙。有什么类似的union all ordered
吗?
解决方案
好的。这是您如何使用“窗口功能”对其进行排序的方法。前提是您使用的是 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
推荐阅读
- vue.js - Vue 组件范围样式未显示 b-form-radio-group 按钮变体
- r - 用于 ARDL 包输出的 Stargazer:“错误:无法识别的对象类型”
- android - Android 工作管理器在我的 oppo 手机中无法使用
- powershell - 在 PowerShell 中使用 PrintDocument 的问题
- sql - 使用 mariaDB 更新父表时出现错误 1452
- loops - 两个 AutoHotkey 循环以不同的时间间隔发送文本
- python-3.x - 关于OOP自参数未填写
- kotlin - 嵌套协方差如何在 Kotlin 中工作?
- java - 如何使用 netbeans 将 javafx 添加到 java 15.01 sdk
- c# - 索引未超出范围时的“索引超出范围异常”