in和exsits在做嵌套查詢的時候使用率很高,那麼在不恰當的地方使用不恰當的嵌套方式,將會對你的sql產生非同小可的響應,筆者曾優化過此種sql,效果天壤之別,那麼怎麼合理使用in和exsits,其實很簡單,明白了原理就不會用錯了;
例子:
delete from temp_7 t where not exists ( select *
from temp_5 tt
where t.t_id = tt.t_id)
等價於:
delete from temp_7 t where t.t_id not in ( select tt.t_id
from temp_5 tt
where t.t_id = tt.t_id)
in 和 exists 性能比較:
分析:
select * from temp_5 t where t.t_id in ( select tt.t_id from temp_7 tt)
等價於
select t.* from temp_5 t,( select distinct t_id from temp_7) tt where t.t_id=tt.t_id
可以看出 temp_7 一定會走全表掃描,而在做等值連接的時 候, temp_5 表可以走索引與 temp_7 表進行連接,所以要想 in 的效率高,內表一點要是小表 。
select * from temp_5 t where exists ( select tt.t_id from temp_7 tt where t.t_id=tt.t_id)
可以看出外表及 temp_5 首先做全表掃描,之後在做等值連接,內表 及 temp_7 可以走索引,所以要想 exists 效率高,那麼外表一定要是小表 。