Oracle 並集交集差集


 

1 並集

一談到並集就會用到union以及union all,兩者的區別如下:
union:對兩個表的並集操作,不包含重復行,相當於distinct,同時進行默認規則的排序。
          默認規則即:按照select后面的查詢字段出現的順序進行排序。
union all:對兩個表的並集操作,包含重復行,且不排序。

具體實例如下:

 1 --創建一張表
 2 create table test
 3  (
 4    id int primary key,
 5    name varchar2(30) not null,
 6    score number not null
 7  );
 8 --插入數據
 9  insert into test values(1,'Aaron',78);
10  insert into test values(2,'Bill',76);
11  insert into test values(3,'Cindy',89);
12  insert into test values(4,'Damon',90);
13  insert into test values(5,'Ella',73);
14  insert into test values(6,'Frado',61);
15  insert into test values(7,'Gill',99);
16  insert into test values(8,'Hellen',56);
17  insert into test values(9,'Ivan',93);
18  insert into test values(10,'Jay',90);
19  commit;

利用union和union all進行查詢

1.1 union all

1 -- union all   
2 select id,name,score from test where id < 4  
3 union all  
4 select id,name,score from test where id > 2 and id < 6 ;
5 --第一個結果集應為1,2,3;第二個結果集應為3,4,5.
6 --最終結果為1,2,3,3,4,5,6.共6行.

結果顯示:

1 -- union all   
2 select id,name,score from test where id > 2 and id < 6
3 union all
4 select id,name,score from test where id < 4 

結果顯示:

未排序,使用union all顯示的結果集順序即為兩條select出現查詢的順序。

1.2 union

1 -- union   
2 select  id,name,score from test where id > 2 and id < 6  
3 union  
4 select  id,name,score from test where id < 4;  
5 --第一個結果集應為1,2,3;第二個結果集應為3,4,5.
6 --最終結果為1,2,3,4,5,6.共5行.

結果顯示:

1 -- union   
2 select score,id,name from test where id > 2 and id < 6  
3 union  
4 select score,id,name from test where id < 4;

結果顯示:

驗證union的結果集排序方式為select后面字段出現的順序。
備注:union前后關聯的列數必須一樣多,前面查詢n個字段,后面也要查詢n個字段。一般情況下查詢結果列名按照關聯前面的命名。

2 交集 intersect
---對兩個結果集進行交集操作,不包括重復行,同時進行默認規則的排序.

實例:

1 --intersect 
2 select EMPNO,ENAME,SAL from EMP
3 intersect
4 select EMPNO,ENAME,SAL from EMP where SAL>'2500';
5 --前面是對EMP的全表查詢的結果集,后面是對sal字段>2500的查詢結果集
6 --求兩個結果集的並集

結果顯示:

 


3 差集 Minus

---對兩個結果集進行差操作,不包括重復行,同時進行默認規則的排序。

實例:

1 --minus 
2 select EMPNO,ENAME,SAL from EMP
3 minus
4 select EMPNO,ENAME,SAL from EMP where SAL>'2500';
5 --前面是對EMP的全表查詢的結果集,后面是對sal字段>2500的查詢結果集
6 --求兩個結果集的差集

結果顯示:

 

以上這幾種操作均可在最后進行人為的排序。把order by 字段放在最后一個結果集后面即可。

 


免責聲明!

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



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