zl程序教程

您现在的位置是:首页 >  后端

当前栏目

解决union查询order by 排序失效的问题

排序 解决 查询 by 失效 order union 问题
2023-09-11 14:15:40 时间

如果要对两个结果集进行合并,我们一般会使用union(去重)查询,SQL如下:

select t1.age,t1.name from table1 t1
union 
select t2.age,t2.name from table2 t2

此时,需要对结果集按年龄进行排序,SQL如果这样写:

select t1.age,t1.name from table1 t1
union
select t2.age,t2.name from table2 t2
order by age    

这样排序是有问题的,排序还是有问题,改造sql如下:

select t11.age,t11.name (select t1.age,t1.name from table1 t1 order by t1.age )t11
union
select t22.age,t22.name (select t2.age,t2.name from table2 t2 order by t2.age)t22

这样写应该是没问题的,但是这样会被优化器优化,所以要加limit限制,最终的SQL如下:

select t11.age,t11.name (select t1.age,t1.name from table1 t1 order by t1.age limit 99999)t11
union
select t22.age,t22.name (select t2.age,t2.name from table2 t2 order by t2.age  limit 99999)t22