SQL 中 union all 与 order by 的同时使用
本文最后更新于 2025-04-28,文章内容可能已经过时。
前言
今天在开发中多个查询语句order by后,使用union all连接时遇到了问题,百度了一下发现想要对表的多次查询结果分别排序再合并是不可行的。union的子句中不允许出现order by,百度到了解决方法,这里记录一下。
正文
当union all和order by如下一起使用时,sql会报错。
select name,age from student order by age
union all
select name,age from person order by age
通用的解决方法有以下几种:
将结果集作为一张临时表然后查询排序。
select * from (select name,age from student order by age union all select name,age from person order by age) order by age
单独对表进行排序后进行并集操作。
select * from (select name,age from student order by age) union all select * from (select name,age from person order by age)
order by + 字段在结果集中的序号。
select name,age from student union all select name,age from person order by 2
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 HaalandCR
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果