今天同时使用mysql的union和order by遇到的坑,这里总结一下。
事情是这样的,我们的任务列表展示的要求是优先展示运行中状态的任务,如果多个运行中状态的任务就按照开始时间进行降序展示。其他的任务状态,不管是失败、完成、还是停止的状态,都统一按照开始时间进行降序。如下图所示,这里是不对的,需要调整。
类似这种情况的数据展示,我优先考虑了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
然后非常自信的点了下执行:
WTF
然后就打开我的度娘:Incorrect usage of UNION and ORDER BY
https://blog.youkuaiyun.com/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)
执行结果,哎呀,并没有我想象的按照日期降序排序。
还需要在子句中添加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)
ok,达到我想要的效果了!