in和exists
in 是把外表和內表做hash 鏈接,而exists是對外表做loop循環,每次loop循環再對內表進行查詢。
一直以來認爲exists比in效率高的說法是不許確的。
若是查詢的兩個表大小至關,那麼用in和exists差異不大。
若是兩個表中一個較小,一個是大表,則子查詢表大的用exists,子查詢表小的用in:
例如:表A(小表),表B(大表)1:select * from A where cc in (select cc from B)
效率低,用到了A表上cc列的索引;select * from A where exists(select cc from B where cc=A.cc)
效率高,用到了B表上cc列的索引。
相反的2:select * from B where cc in (select cc from A)
效率高,用到了B表上cc列的索引;select * from B where exists(select cc from A where cc=B.cc)
效率低,用到了A表上cc列的索引。
not in 和not exists
若是查詢語句使用了not in 那麼內外表都進行全表掃描,沒有用到索引;而not extsts 的子查詢依然能用到表上的索引。因此不管那個表大,用not exists都比not in要快。
not in 邏輯上不徹底等同於not exists,若是你誤用了not in,當心你的程序存在致命的BUG:
請看下面的例子:
create table t1 (c1 number,c2 number);
create table t2 (c1 number,c2 number);
insert into t1 values (1,2);
insert into t1 values (1,3);
insert into t2 values (1,2);
insert into t2 values (1,null);
select * from t1 where c2 not in (select c2 from t2);
no rows found
select * from t1 where not exists (select 1 from t2 where t1.c2=t2.c2);
c1 c2
1 3
正如所看到的,not in 出現了不指望的結果集,存在邏輯錯誤。若是看一下上述兩個select語句的執行計劃,也會不一樣。後者使用了hash_aj。
所以,請儘可能不要使用not in(它會調用子查詢),而儘可能使用not exists(它會調用關聯子查詢)。若是子查詢中返回的任意一條記錄含有空值,則查詢將不返回任何記錄,正如上面例子所示。
除非子查詢字段有非空限制,這時可使用not in ,而且也能夠經過提示讓它使用hasg_aj或merge_aj鏈接