sql中in和exists的區別

2021-08-15 08:35:57 字數 1574 閱讀 7513

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

相反的:

1 select * from b where cc in(select cc from a)  –>效率高,用到了b表上cc列的索引

2 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,請看下面的例子:

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

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

3 insert into #t1 values(1,2);

4 insert into #t1 values(1,3);

5 insert into #t2 values(1,2);

6 insert into #t2 values(1,null);

7 select * from #t1 where c2 not in(select c2 from #t2);  –>執行結果:無

8 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 與 = 的區別

1 select name from student where name in(『zhang』,』wang』,』zhao』);

與1 select name from student where name=』zhang』 or name=』wang』 or name=』zhao』

的結果是相同的。

詳解sql中exists和in的語法與區別

exists和in的區別很小,幾乎可以等價,但是sql優化中往往會注重效率問題,今天咱們就來說說exists和in的區別。exists語法 select from table whealqkydre exists 子查詢 將主查詢的結果,放到子查詢結果中進行校驗,如子查詢有資料,則校驗成功,那麼符合...

關於oracle中in和exists的區別

一般來說,這兩個是用來做兩張 或更多 表聯合查詢用的,in是把外表和內錶作hash 連線,而exists 是對外表作loop 迴圈,假設有a b兩個表,使用時是這樣的 1 select from a where id in select id from b 使用in 2 select from a ...

關於oracle中in和exists的區別

本文 select from a where id in select id from b 以上查詢使用了in語句,in 只執行一次,它查出b表中的所有id欄位並快取起來.之後,檢查a表的id是否與b表中的id相等,如果相等則將a表的記錄加入結果集中,直到遍歷完a表的所有記錄.它的查詢過程類似於以下...