In和Exist的效率問題

2021-07-11 10:54:26 字數 874 閱讀 9362

總有人說exist效率比in高,但真得如此嗎?

in:

select * from t1 where x in ( select y from t2 )

觀察該sql可知,該查詢需要先執行子查詢,得到結果後執行外查詢。因此該sql可以轉換為:

select * from t1 where x = y1; 

select * from t1 where x = y2; 

select * from t1 where x = yn; 

即實際上首先找出子查詢中所有可能的值,然後多次執行外查詢。由此可見,有多少個y值,查詢就會進行多少次,因此y值越少則越快。因此in適合於外表大,而子查詢返回的結果比較少的情況。

exists:

select * from t1 where exists ( select null from t2 where y = x )

觀察該sql可知,該查詢需要首先確定x的值,然後才能執行子查詢。而一開始x的值無法可知,因此只能全表掃瞄。因此該sql可以轉換為:

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;

因此t1永遠是個表掃瞄!因此t1絕對不能是個大表,而t2可以很大,因為y=x.x可以走t2.y的索引。

綜合以上對in/exists的討論,我們可以得出乙個基本通用的結論:in適合於外表大而內錶小的情況;exists則相反,適用於外表小而內錶大的情況。

SQL中exist和in的執行效率問題

select from a where id in select id from b select a.from a a where exists select 1 from b b where a.id b.id 結論 1 看表資料規模,a表 b表,使用in a表2 無論什麼情況,not exis...

sql in 和 exist的區別

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

sql in 和 exist的區別

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