union 或者 union all 與 order by 的聯合使用


首先清楚:多個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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM