union 或者 union all 与 order by 的联合使用

时间:2022-10-28 22:45:43

首先清楚:多个select 语句 union 时不是简单的将查询结果拼接起来 而是将sql拼接起来编译(做为一个sql语句),然后去执行。


注:

union 连接的语句中只会出现一个order by (不包含子查询中的)否则会报  sql未正确结束的错误。


解决方法:

将order by 语句放到子查询中


例子:

1、将排序后的查询结果拼接起来
select * from(select  *  from table order by a)

union

select * from (select * from table1 order by b)

union

select * from (select * from table2 order by c);

2、将排序后的查询结果拼接起来,再排序

select * from(select  *  from table order by a)

union

select * from (select * from table1 order by b)

union

select * from (select * from table2 order by c)

order by d;----此处的order by 是将最后的拼接结果集排序  打乱了之前通过 a、b、c的排序。