【SQL】兩個帶order by查詢進行union all報ORA-00933錯誤的解決方法
阿新 • • 發佈:2018-12-23
在oracle SQL中,要求order by是select語句的最後一個語句,而且一個select語句中只允許出現一個order by語句,而且order by必須位於整個select語句的最後。
當時是要將一個十分複雜的檢索明細查詢和一個十分複雜的檢索彙總查詢的結果進行合併,以簡化開發。
開發人員選擇使用了union all來連線兩個結果集。
※使用union all 而不用union來連線兩個檢索結果集的原因是,union實際上做了兩部分動作:結果集合並+排序,而union all只進行結果集簡單合併,不做排序。
我在這裡簡要做個模擬。
/////////////////////////////////////////////////////
// 1)兩個表中的資料
/////////////////////////////////////////////////////
SQL> select * from tb1;
C1 C2
----- ----------
a1001 1
a1002 2
a1003 3
SQL> select * from tb2;
C1 C2
----- ----------
b2001 1
b2002 2
b2003 3
/////////////////////////////////////////////////////
// 2)兩個帶order by的查詢
/////////////////////////////////////////////////////
SQL> select * from tb1 order by c1 desc;
C1 C2
----- ----------
a1003 3
a1002 2
a1001 1
SQL> select * from tb2 order by c1 desc;
C1 C2
----- ----------
b2003 3
b2002 2
b2001 1
/////////////////////////////////////////////////////
// 3)接下來,我們將兩個查詢的結果用union all合併起來
/////////////////////////////////////////////////////
// 可以看到 直接用union all連線兩個子查詢時,報出了ORA-00933錯誤
// 因為 oracle 認為第一個order by結束後整個select語句就該結束了,
// 但是發現後面沒有逗號(;)或斜線(/)結束符,反而發現了 union all
/////////////////////////////////////////////////////
SQL> select * from tb1 order by c1 desc
2 union all
3 select * from tb2 order by c1 desc;
union all
*
第 2 行出現錯誤:
ORA-00933: SQL 命令未正確結束
/////////////////////////////////////////////////////
// 4)接下來,演示一下如何使用with。。as。。select。。
// 將兩個查詢的結果用union all合併而且能夠執行
/////////////////////////////////////////////////////
SQL> with
2 s1 as (
3 select * from tb1 order by c1 desc
4 ),
5 s2 as (
6 select * from tb2 order by c1 desc
7 )
8 select * from s1
9 union all
10 select * from s2;
C1 C2
----- ----------
a1003 3
a1002 2
a1001 1
b2003 3
b2002 2
b2001 1
已選擇6行。