A: In:是把外表和內表作Hash 鏈接,而exists 是對外表做loop 循環,每次loop循環再對內表進行查詢。oop
當查詢兩個表的大小至關時,用In 和 exists差異不大。spa
若是兩個表中一個表較小,一個表較大,那麼子查詢表大的用exists,子查詢表小的用In,效率會高的。索引
也就是說 IN適合於外表大而內表小的狀況;EXISTS適合於外表小而內表大的狀況,這樣效率會高的效率
例如 :表a(小表),表b(大表)select
1.select * from a where aid in (select aid from b) --->效率低:全程掃描b表,用到a 表上的aid的索引,由於a表小,b表大循環
上面in的語句能夠理解爲:
select *
from a, ( select distinct aid from b) b1
where a.aid = b1.aid.查詢
select * from a where exists (select aid from b where b.aid = a.aid) --->效率高: 全程掃描a表,用到b表上的aid的索引。由於b表大。margin
上面的exists的語句能夠理解爲:di
for aid in ( select * from a)
loop
if ( exists ( select aid from b where b.aid= a.aid )
then
OUTPUT THE RECORD!
end if
end looploop
2. select * from b where aid in (select aid from a)----效率高:全程掃描a 表,用到b表上的aid 索引
select * from b where exists (select aid from a were a.aid= b.aid) --->效率低:全程掃描b 表:用到a 表上的aid索引。
B: Not in 和Not Exists 的 效率
若是查詢語句使用了Not In,那麼內外表所有進行掃描,沒有乃至索引
Not Exist用到子表中的索引進行查詢,因此不管兩個表中哪一個表大,Not exists 都要比Not in 要快。