a: in:是把外表和內錶做hash 連線,而exists 是對外表作loop 迴圈,每次loop迴圈再對內表進行查詢。
當查詢兩個表的大小相當時,用in 和 exists差別不大。
如果兩個表中乙個表較小,乙個表較大,那麼子查詢表大的用exists,子查詢錶小的用in,效率會高的。
也就是說in適合於外表大而內錶小的情況;exists適合於外表小而內錶大的情況,這樣效率會高的
例如 :表a(小表),表b(大表)
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表大。
上面的exists的語句可以理解為:
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 loop
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 要快。
測試in 與exists 查詢效率
測試1w條資料和100w條資料下 in 和 exists的區別 t user 為100w條,t user memory 為1w條 1 in的原理 在select from a where id in select id from b 中,in 中的子查詢只執行一次,它查詢出b表中的所有id值並快取起...
in和exists的SQL執行效率分析
in和exists的sql執行效率分析 a,b兩個表,1 當只顯示乙個表的資料如a,關係條件只乙個如id時,使用in更快 select from a where id in select id from b 2 當只顯示乙個表的資料如a,關係條件不只乙個如id,col1時,使用in就不方便了,可以使...
mysql中in與exists效率比較
這條語句適用於a錶比b表大的情況 select from ecs goods a where cat id in select cat id from ecs category 這條語句適用於b錶比a表大的情況 select from ecs goods a where exists select ...