天天看點

淺談sql中的in與not in,exists與not exists的差別

1、in和exists

in是把外表和内表作hash連接配接,而exists是對外表作loop循環,每次loop循環再對内表進行查詢,一直以來認為exists比in效率高的說法是不準确的。如果查詢的兩個表大小相當,那麼用in和exists差别不大;如果兩個表中一個較小一個較大,則子查詢表大的用exists,子查詢表小的用in;

例如:表A(小表),表B(大表)

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列的索引。      

相反的:

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列的索引。      

2、not in 和not exists

not in 邏輯上不完全等同于not exists,如果你誤用了not in,小心你的程式存在緻命的BUG,請看下面的例子:

create table #t1(c1 int,c2 int);

create table #t2(c1 int,c2 int);

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);  -->執行結果:無

select * from #t1 where not exists(select 1 from #t2 where #t2.c2=#t1.c2)  -->執行結果:1  3      

正如所看到的,not in出現了不期望的結果集,存在邏輯錯誤。如果看一下上述兩個select 語句的執行計劃,也會不同,後者使用了hash_aj,是以,請盡量不要使用not in(它會調用子查詢),而盡量使用not exists(它會調用關聯子查詢)。如果子查詢中傳回的任意一條記錄含有空值,則查詢将不傳回任何記錄。如果子查詢字段有非空限制,這時可以使用not in,并且可以通過提示讓它用hasg_aj或merge_aj連接配接。

如果查詢語句使用了not in,那麼對内外表都進行全表掃描,沒有用到索引;而not exists的子查詢依然能用到表上的索引。是以無論哪個表大,用not exists都比not in 要快。

3、in 與 = 的差別

select name from student where name in('zhang','wang','zhao');      

select name from student where name='zhang' or name='wang' or name='zhao'      

的結果是相同的。