先排序然后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

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM