IN与EXISTS优化

用inner join,不要用in或者exists

当B表的数据集必须小于A表的数据集时,用in优于exists,
当A表的数据集系小于B表的数据集时,用exists优于in

优化原则:小表驱动大表,即小的数据集驱动大的数据集。

############# 原理 (RBO) #####################

-- A表 > B表:in select * from A where id in (select id from B) -- 等价于: for select id from B for select * from A where A.id = B.id 

当B表的数据集小于A表的数据集时,用in优于exists。

-- A表 < B表:exists select * from A where exists (select 1 from B where B.id = A.id) -- 等价于 for select * from A for select * from B where B.id = A.id 

当A表的数据集小于B表的数据集时,用exists优于in。

注意:A表与B表的ID字段应建立索引。

例如:

 /** 执行时间:0.313s **/ SELECT SQL_NO_CACHE * FROM rocky_member m WHERE EXISTS ( SELECT 1 FROM rocky_vip_appro a WHERE m.ID = a.user_id AND a.passed = 1 ); /** 执行时间:0.160s **/ SELECT SQL_NO_CACHE * FROM rocky_member m WHERE m.ID in( SELECT ID FROM rocky_vip_appro WHERE passed = 1 ); 

not in 和 not exists 用法类似。

全文:
in和exists
in 是把外表和内表作hash连接,而 exists 是对外表作loop循环,每次loop循环再对内表进行查询。

一直以来认为exists比in效率高的说法是不准确的。
如果查询的两个表大小相当,那么用in和exists差别不大。

如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

例如:表A(小表),表B(大表)
1: select * from A where cc in (select cc from B)效率低,用到了A表上cc列的索引;
2: select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。

相反的:
1: select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
2: select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。

not in 和not exists
如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;
而not extsts 的子查询依然能用到表上的索引。
所以无论那个表大,用not exists都比not in要快 。

in 与 =的区别

select name from student where name in ('zhang','wang','li','zhao');` 与 select name from student where name='zhang' or name='li' or name='wang' or name='zhao' 

结果是相同的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讓丄帝愛伱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值