MySQL优化之in、exists、join

一、inner join 、 in 、exists
1     explain
2     select a.id
3     from application as a
4     where exists(
5       select 1
6       from dispatch_app_history as d
7       where d.bomber_id = 165 and d.application_id = a.id
8     );
 
   
1     explain
2     select a.id
3     from application as a
4     where a.id in (
5       select d.application_id
6       from dispatch_app_history as d
7       where d.bomber_id = 165
8     );
 
    
1     explain
2     select a.id
3     from application as a
4     inner join dispatch_app_history as d on d.application_id = a.id
5     where d.bomber_id = 165;
分析:子查询需要application_id来关联外部表application,因为需要application_id字段,所以MySQL认为无法先执行这个子查询,而对application表进行全表查询。
结论:子查询、join查询具体性能怎么样需要根据实际情况决定
 
 
二、not in、not exists
    1、执行速度  
1      explain
2      select *
3      from dispatch_app as d
4      where d.application_id not in(
5         select dh.application_id
6         from dispatch_app_history as dh
7      );                       
     
 
    
1      explain
2      select *
3      from dispatch_app as d
4      where not exists (
5         select 1
6         from dispatch_app_history as dh
7         where d.application_id = dh.application_id
8      )
   
  结论:不考虑其他情况,通常情况下not exists的执行效率要高于not in
 
    2、条件中含有null
1      select *
2      from bomber as b
3      where not exists(
4         select 1
5         from dispatch_app_history as d
6         where d.partner_id = b.partner_id
7      )
8      group by b.partner_id;

 
     
1      select *
2      from bomber as b
3      where b.partner_id not in(
4         select distinct d.partner_id
5         from dispatch_app_history as d
6      );
  
结论:对于not in,条件中有null值的时候会直接停止执行返回null结果。对于not exists,条件中有null时会清除null后执行。in、exists的执行与not existst相同
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/yuluodisuihe/p/9671894.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值