Oracle 做並集-union、差集minus、交集intersect

創建測試數據:

create table A(ID NUMBER,NAME VARCHAR2(10));
insert into A
	select 1 as ID,'北京' as NAME from dual union all
	select 2 as ID,'上海' as NAME from dual union all
	select 3 as ID,'廣州' as NAME from dual;


create table B(ID NUMBER,NAME VARCHAR2(10));
insert into B
	select 1 as ID,'北京' as NAME from dual union all
	select 2 as ID,'上海' as NAME from dual union all
	select 4 as ID,'深圳' as NAME from dual;

commit;

A表與B表 

並集:

union(對合成的結果去重)

select * from A 
union 
select * from B;

 

union all(完全合成兩個表)

select * from A 
union all
select * from B;

交集:intersect(取在A表與B表同時存在的數據) 

select * from A 
intersect
select * from B;

差集:minus(取在A表中存在但是B表中不存在的數據)

select * from A 
minus
select * from B;

注意,這裏的函數都需要兩個表有相同的表結構。

有個小技巧,可以查詢Oracle數據庫的指定行到指定行的數據:

select * from A where ROWNUM <=3
minus
select * from A where ROWNUM <=2;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章