天天看點

order by與union all

**【SQL】兩個帶order by查詢進行union all報ORA-00933錯誤的解決方法** 
           

在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行。