您当前的位置: 首页 >  nio

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

杨林伟 发布时间:2020-11-06 09:26:09 ,浏览量:4

如果要对两个结果集进行合并,我们一般会使用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
关注
打赏
1688896170
查看更多评论

杨林伟

暂无认证

  • 4浏览

    0关注

    3183博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.4764s