in和exists的效率問題

2021-10-12 04:25:18 字數 858 閱讀 2447

in 是把外表和內錶作hash鏈結

exists是對外表作loop迴圈,每次loop迴圈再對內表進行查詢。

一直以來總認為exists比in的效率高,這種說法是不準確的。如果查詢的兩個表大小相當的話,那麼用in和exists的效率差別不大。

如果兩個表中乙個較小的表a,乙個大表b,兩個表都有字段cc

則有以下幾種情況:

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

對於not in和not exists

如果查詢語句使用了not in,那麼內外表都進行全表掃瞄,沒有用到索引;

而not exists的子查詢依然能用到表上的索引,所以無論哪個表大,用not exists都比in效率更高。

in 和 exists效率問題

not in select distinct md001 from bommd where md001 not in select mc001 from bommc not exists,exists的用法跟in不一樣,一般都需要和子表進行關聯,而且關聯時,需要用索引,這樣就可以加快速度 selec...

sql中in和exists的區別效率問題

in是把外表和內錶作hash 連線,而exists 是對外表作loop 迴圈,每次loop 迴圈再對內表進行查詢。一直以來認為exists 比in 效率高的說法是不準確的。如果查詢的兩個表大小相當,那麼用in 和exists 差別不大。如果兩個表中乙個較小,乙個是大表,則子查詢表大的用exists,...

SQL語句中IN和EXISTS的效率問題

in select from a where id in select id from b 此處select id from b只會執行一次,將所有資料快取到記憶體,然後遍歷a表中的每條資料進行判斷是否存在。exist select from a as a where exists select i...