一直聽到的都是說(shuō)盡量用exists不要用in,因?yàn)閑xists只判斷存在而in需要對(duì)比值,所以exists比較快,但看了看網(wǎng)上的一些東西才發(fā)現(xiàn)根本不是這么回事。
下面這段是抄的
Select * from T1 where x in ( select y from T2 )
執(zhí)行的過(guò)程相當(dāng)于:
select *
from t1, ( select distinct y from t2 ) t2
where t1.x = t2.y;
select * from t1 where exists ( select null from t2 where y = x )
執(zhí)行的過(guò)程相當(dāng)于:
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop
從我的角度來(lái)說(shuō),in的方式比較直觀,exists則有些繞,而且in可以用于各種子查詢,而exists好像只用于關(guān)聯(lián)子查詢(其他子查詢當(dāng)然也可以用,可惜沒(méi)意義)。
由于exists是用loop的方式,所以,循環(huán)的次數(shù)對(duì)于exists影響最大,所以,外表要記錄數(shù)少,內(nèi)表就無(wú)所謂了,而in用的是hash join,所以內(nèi)表如果小,整個(gè)查詢的范圍都會(huì)很小,如果內(nèi)表很大,外表如果也很大就很慢了,這時(shí)候exists才真正的會(huì)快過(guò)in的方式。
下面這段還是抄的
not in 和not exists
如果查詢語(yǔ)句使用了not in 那么內(nèi)外表都進(jìn)行全表掃描,沒(méi)有用到索引;
而not extsts 的子查詢依然能用到表上的索引。
所以無(wú)論那個(gè)表大,用not exists都比not in要快。
也就是說(shuō),in和exists需要具體情況具體分析,not in和not exists就不用分析了,盡量用not exists就好了。
我的微博
http://t.sina.com.cn/1401900445