如果我們需要將兩個select語句的結果作為一個整體顯示出來,我們就需要用到union或者union all關鍵字。union(或稱為聯合)的作用是將多個結果合並在一起顯示出來。
union和union all的區別是,union會自動壓縮多個結果集合中的重復結果,而union all則將所有的結果全部顯示出來,不管是不是重復。
Union:對兩個結果集進行並集操作,不包括重復行,同時進行默認規則的排序;
Union all:對兩個結果集進行並集操作,包括重復行,不進行排序;
Intersect:對兩個結果集進行交集操作,不包括重復行,同時進行默認規則的排序;
Minus:對兩個結果集進行差操作,不包括重復行,同時進行默認規則的排序。
下面以實例說明Union與Union all的區別:
1、首先創建一張jack表:
SQL> create table jack 2 ( 3 id int primary key, 4 name varchar2(30) not null, 5 score number not null 6 ); 表已創建。 QL> insert into jack values(1,'Aaron',78); SQL> insert into jack values(2,'Bill',76); SQL> insert into jack values(3,'Cindy',89); SQL> insert into jack values(4,'Damon',90); SQL> insert into jack values(5,'Ella',73); SQL> insert into jack values(6,'Frado',61); SQL> insert into jack values(7,'Gill',99); SQL> insert into jack values(8,'Hellen',56); SQL> insert into jack values(9,'Ivan',93); SQL> insert into jack values(10,'Jay',90); SQL> commit; SQL> select * from jack; ID NAME SCORE ---------- -------------------- ---------- 1 Aaron 78 2 Bill 76 3 Cindy 89 4 Damon 90 5 Ella 73 6 Frado 61 7 Gill 99 8 Hellen 56 9 Ivan 93 10 Jay 90 已選擇10行。
2、使用union與union all進行查詢:
SQL> select * from jack where id<4 2 union 3 select * from jack where id >2 and id<6; ID NAME SCORE ---------- -------------------- ---------- 1 Aaron 78 2 Bill 76 3 Cindy 89 4 Damon 90 5 Ella 73 SQL> select * from jack where id<4 2 union all 3 select * from jack where id >2 and id<6; ID NAME SCORE ---------- -------------------- ---------- 1 Aaron 78 2 Bill 76 3 Cindy 89 3 Cindy 89 4 Damon 90 5 Ella 73 已選擇6行。
從上面的兩個查詢中可以看出它們的區別之一在於對重復結果的處理。
3、調整兩個子查的順序:
SQL> select * from jack where id >2 and id<6 2 union 3 select * from jack where id<4 ; ID NAME SCORE ---------- -------------------- ---------- 1 Aaron 78 2 Bill 76 3 Cindy 89 4 Damon 90 5 Ella 73 SQL> select * from jack where id >2 and id<6 2 union all 3 select * from jack where id<4 ; ID NAME SCORE ---------- -------------------- ---------- 3 Cindy 89 4 Damon 90 5 Ella 73 1 Aaron 78 2 Bill 76 3 Cindy 89 已選擇6行。
它們兩者的區別之二在於對排序的處理。Union all將按照關聯的次序組織數據,而Union將進行依據一定規則進行排序。
4、驗證Union排序規則(調整一下查詢字段的順序):
SQL> select score,id,name from jack where id >2 and id<6 2 union 3 select score,id,name from jack where id<4 ; SCORE ID NAME ---------- ---------- -------------------- 73 5 Ella 76 2 Bill 78 1 Aaron 89 3 Cindy 90 4 Damon
可以看到之前的查詢是基於id,name,score的字段順序,那么結果集將按照id優先進行排序;而現在新的字段順序也改變了產訊結果的排序,由此可以按照union的排序是按照第一個字段進行排序的,但是我們也可以進行干預,指定按某個字段進行排序。
5、指定某個字段進行排序
SQL> select * from 2 ( 3 select score,id,name from jack where id>2 and id<7 4 union 5 select score,id,name from jack where id<4 6 union 7 select score,id,name from jack where id>8 8 ) 9 order by id desc; SCORE ID NAME ---------- ---------- -------------------- 90 10 Jay 93 9 Ivan 61 6 Frado 73 5 Ella 90 4 Damon 89 3 Cindy 76 2 Bill 78 1 Aaron 已選擇8行。