目录

今日说码

点滴记录中国代码进程

X

SQL 中 union all 与 order by 的同时使用

前言

  今天在开发中多个查询语句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
通用的解决方法有以下几种:
  1. 将结果集作为一张临时表然后查询排序。
    select * from (select name,age from student order by age
    union all
    select name,age from person order by age) order by age
    
  2. 单独对表进行排序后进行并集操作。
    select * from (select name,age from student order by age)
    union all
    select * from (select name,age from person order by age)
    
  3. order by + 字段在结果集中的序号。
    select name,age from student
    union all
    select name,age from person
    order by 2
    

标题:SQL 中 union all 与 order by 的同时使用
作者:96XL
地址:https://solo.96xl.top/articles/2019/08/01/1564642274735.html