Oracle Minus關鍵字
SQL中的MINUS關鍵字
SQL中有一個MINUS關鍵字,它運用在兩個SQL語句上,它先找出第一條SQL語句所產生的結果,然後看這些結果有沒有在第二個SQL語句的結果中。如果有的話,那這一筆記錄就被去除,而不會在最後的結果中出現。如果第二個SQL語句所產生的結果並沒有存在於第一個SQL語句所產生的結果內,那這筆資料就被拋棄,其文法如下:
[SQL Segment 1]
MINUS
[SQL Segment 2]
--------------------------------------------
//建立表1
create table test1
(
name varchar(10),
sex varchar(10),
);
insert into test1 values('test','female');
insert into test1 values('test1','female');
insert into test1 values('test1','female');
insert into test1 values('test11','female');
insert into test1 values('test111','female');
//建立表2
create table test2
(
name varchar(10),
sex varchar(10),
);
insert into test1 values('test','female');
insert into test1 values('test2','female');
insert into test1 values('test2','female');
insert into test1 values('test22','female');
insert into test1 values('test222','female');
-------------------------------------------
select * from test1 minus select * from test2;
結果:
NAME SEX
---------- ----------
test1 female
test11 female
test111 female
-----------------------------------------------------------
select * from test2 minus select * from test1;
結果:
NAME SEX
---------- ----------
test2 female
test22 female
test222 female
結論:Minus返回的總是左邊表中的資料,它返回的是差集。注意:minus有剃重作用
==========================================================
下面是我做的實驗,很明顯能夠看出MINUS的效率,made_order共23萬筆記錄,charge_detail共17萬筆記錄
效能比較:
SELECT order_id FROM made_order
MINUS
SELECT order_id FROM charge_detail
1.14 sec
SELECT a.order_id FROM made_order a
WHERE NOT exists (
SELECT order_id
FROM charge_detail
WHERE order_id = a.order_id
)
18.19 sec
SELECT order_id FROM made_order
WHERE order_id NOT in (
SELECT order_id
FROM charge_detail
)
20.05 sec
還有其它一下關鍵字:
INTERSECT (交集)
UNION ALL 並集