標籤:style io 資料 art ar div new sql
Oracle Minuskeyword
SQL中的MINUSkeyword
SQL中有一個MINUSkeyword,它運用在兩個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
還有其他一下keyword:
INTERSECT (交集)
UNION ALL 並集