2 回答

TA貢獻188條經(jīng)驗 獲得超91個贊
EXISTS的執(zhí)行流程
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
對于in和exists的性能區(qū)別:
如果子查詢得出的結(jié)果集記錄較少,主查詢中的表較大且又有索引時應(yīng)該用in,反之如果外層的主查詢記錄較少,
子查詢中的表大,又有索引時使用exists。其實我們區(qū)分in和exists
主要是造成了驅(qū)動順序的改變(這是性能變化的關(guān)鍵),如果是exists
,那么以外層表為驅(qū)動表,先被訪問,如果是IN,那么先執(zhí)行子查詢,所以我們
會以驅(qū)動表的快速返回為目標,那么就會考慮到索引及結(jié)果集的關(guān)系了
另外IN時不對NULL進行處理如:
select 1 from dual where null
in (0,1,2,null)
為空
2.NOT IN與NOT EXISTS:
NOT EXISTS的執(zhí)行流程
select .....from rollup R where not exists ( select 'Found' from title T where R.source_id = T.Title_ID);
可以理解為:
for x in ( select * from rollup )loop
if ( not exists ( that query ) ) then
OUTPUT
end if;
end;
注意:NOT EXISTS與NOT IN不能完全互相替換,看具體的需求。如果選擇的列可以為
空,則不能被替換。
?
- 2 回答
- 0 關(guān)注
- 3333 瀏覽
添加回答
舉報