数据库教程:先排序然后union all失效,mysql数据库多个表union all查询并排序的结果为什么错误

先排序然后union all失效,mysql数据库多个表union all查询并排序的结果为什么错误 …

 

mysql数据库多个表union all查询并排序的结果为什么错误?

 群主,我想进行一个表的查询,先把表中某个字段的内容查出,然后其他的再排序,我用union all连接两个表的查询结果排序是错的

比如我的sql语句:

select * from student t where t.name=’aa’ order by t.date desc

union all

select from student_1 s where s.name=’bb’ order by s.date desc

这两个查询出来的结果拼接到一起,按照原定的根据时间排序被打乱,现在想先将aa的查询出来,后面属于bb的按照时间进行排序。

 

错误原因:

原因是order by 的优先级比 union all要低,所以一旦同时出新order 和 union 

会先执行union , 再执行order 

 

解决方案:

select * from student  t   order by (case when t.name=’aa’ then 0 else 1 end), t.date desc


 

需要了解更多数据库技术:先排序然后union all失效,mysql数据库多个表union all查询并排序的结果为什么错误,都可以关注数据库技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/dtteaching/827906.html

(0)
上一篇 2021年9月18日
下一篇 2021年9月18日

精彩推荐