解决UNION ALL合并两个结果集后排序的问题

日常开发中,如果实用UNION ALL合并两个已经排好序的结果集的时候,需求是第二个结果集数据排在第一个结果集数据下面,单纯的实用order by是无效的,因为order by的优先级比UNION ALL低。

例如:

select one.*  from (select t1.* from table1 t1 where 1=1 and t1.day >3 order by t1.create_date desc)  one 

UNION ALL

select two.*  from (select t2.* from table2 t2 where 1=1 and t1.day <=3 order by t2.create_date desc)  two

此时查询结果并不是安好two排序好之后  排在  one下面,如果要实现这样的需求,可以使用一个临时字段作为排序字段,该字段的作用是使合并后的结果集有一个统一的排序字段,合并前的结果集分别给默认值1和2,这样在合并后的结果集可以排序了.

select all.* from (select one.*  from (select t1.*,'1' as 'sortBy' from table1 t1 where 1=1 and t1.day >3 order by t1.create_date desc)  one 

UNION ALL

select two.*  from (select t2.* ,'2'  as  'sortBy' from table2 t2 where 1=1  and t.2day <=3 order by t2.create_date desc)  two) all where 1=1 order by all.sortBy asc

解决方案的巧妙之处就是,利用一个自定义的字段实现两个结果集的合并后排序。

转载自:https://www.cnblogs.com/mark8080/p/8431419.html

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值