in与exists别乱用

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值