首先清楚:多個select 語句 union 時不是簡單的將查詢結果拼接起來 而是將sql拼接起來編譯(做為一個sql語句),然后去執行。
注:
union 連接的語句中只會出現一個order by (不包含子查詢中的)否則會報 sql未正確結束的錯誤。
解決方法:
將order by 語句放到子查詢中
例子:
1、將排序后的查詢結果拼接起來
select * from(select * from table order by a)
union
select * from (select * from table1 order by b)
union
select * from (select * from table2 order by c);
2、將排序后的查詢結果拼接起來,再排序
select * from(select * from table order by a)
union
select * from (select * from table1 order by b)
union
select * from (select * from table2 order by c)
order by d;----此處的order by 是將最后的拼接結果集排序 打亂了之前通過 a、b、c的排序。
---------------------
作者:搬長城的紅磚
來源:CSDN
原文:https://blog.csdn.net/yin_jia_521/article/details/65990413
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!