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