[SQL使用经验]选用 IN 还是 EXISTS,哪个性能更好
一、EXISTS 并非總比IN 快,究竟應該選用 IN 還是 EXISTS ,可參考以下分析:
1、Select * from t1 where x in ( select y from t2 )
相當于
select *
? from t1, ( select distinct y from t2 ) t2
?where t1.x = t2.y;
2、select * from t1 where exists ( select null from t2 where y = x )
相當于
?? 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
如果t2的記錄很多而t1的記錄相對較少的話,建議采用第二種寫法;相反,如果t1的記錄很多而t2的記錄相對較少,則建議采用第一種寫法。
其它情況,則需要仔細分析再決定是選擇IN還是選擇EXISTS
二、NOT IN 并不等價于NOT EXISTS
例如下面這兩個句子,只有在t1.c1不為NULL的時候,兩者返回的記錄才是相同的,大家在用NOT EXISTS來替換NOT IN 時可能會忽略掉這一點
select t1.*
? from table1 t1
?where not exists
?(select t2.c1 from table2 t2 where t2.c1 = t1.c1)
select t1.*
? from table1 t1
?where t1.c1 not in (select t2.c1 from table2 t2)
轉載于:https://www.cnblogs.com/cxd4321/archive/2007/05/29/764178.html
總結
以上是生活随笔為你收集整理的[SQL使用经验]选用 IN 还是 EXISTS,哪个性能更好的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 魔兽世界怀旧服血色修道院有什么任务 任务
- 下一篇: 1.78版正式发布,不好意思,让大家多等