下面的这段sql中使用了union,因业务需要又需要用到 时间order by排序
select * from `user` where user_type='owner' order by creat_time
union
select * from `user` where user_type='employee' order by creat_time ;
执行时报错了 ,报错如下:

解决方案如下,将2个sql使用(),就执行成功了:
(select * from `user` where user_type='owner' order by creat_time)
union
(select * from `user` where user_type='employee' order by creat_time );
你以为这样就好了么?不,还没有结束因为这个时候看到的order by的顺序仍然是错乱的,下面把这个sql 在进行一次更改
select a.* from (select * from `user` where user_type='owner'
union
select * from `user` where user_type='employee' ) a order by a.creat_time desc;
这个时候执行才是我所需要的顺序

本文讲述了如何在SQL查询中使用UNION操作符同时保持时间排序的正确性,通过嵌套子查询和orderby语句的调整,确保最终结果按创建时间正确排序的过程。

6341

被折叠的 条评论
为什么被折叠?



