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 效率高,那么外表一定要是小表 。