mysql中我同时使用ORDER BY和UNION遇到的问题

  今天同时使用mysql的union和order by遇到的坑,这里总结一下。

  事情是这样的,我们的任务列表展示的要求是优先展示运行中状态的任务,如果多个运行中状态的任务就按照开始时间进行降序展示。其他的任务状态,不管是失败、完成、还是停止的状态,都统一按照开始时间进行降序。如下图所示,这里是不对的,需要调整。

img

  类似这种情况的数据展示,我优先考虑了union all,sql如下:

select * from data_collect_task_instance where task_instance_status = 1 order by start_time desc
UNION ALL 
select * from data_collect_task_instance where task_instance_status in(0,2,3) order by start_time desc

  然后非常自信的点了下执行:

img

  WTF

img

  然后就打开我的度娘:Incorrect usage of UNION and ORDER BY

https://blog.csdn.net/loophome/article/details/51308631

  最后发现问题出在了mysql中的union all和order by同时使用的时候,需要将select套为子句

(select * from data_collect_task_instance where task_instance_status = 1 order by start_time desc)
UNION ALL 
(select * from data_collect_task_instance where task_instance_status in(0,2,3) order by start_time desc)

  执行结果,哎呀,并没有我想象的按照日期降序排序。

img

  还需要在子句中添加limit才能够导致order by生效,但是我们的查询结果理论上是可以查询所有的,我limit后面应该给个多大的数呢,考虑到业务场景中不可能出现这么多的任务数量(现场目前最多100个),我就给个10000吧(坑已经挖好了)

(select * from data_collect_task_instance where task_instance_status = 1 order by start_time asc limit 10000)
UNION ALL 
(select * from data_collect_task_instance where task_instance_status in(0,2,3) order by start_time desc limit 10000)

img

  ok,达到我想要的效果了!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值