一、引入
SQL1:
select count(1)
from
table1 a inner join table2 b on a.tid=b.tid
inner join table3 c on a.tid=c.tid
where
a.tid2 in
(select d.tid2 from table4 d);
SQL2:
select count(1)
from
table1 a inner join table2 b on a.tid=b.tid
inner join table3 c on a.tid=c.tid
inner join table4 d on a.tid2=d.tid2;
对于这两条语句我们可以思考:
- 两条语句的执行结果一致吗?
- in和join的效率哪个高一些?
二、结果分析
对于in来说,结果不会产生重复数据;而对于join来说,如果驱动表或被驱动表所关联的列有重复值,结果会有重复值。
因为join做的是全连接,会把值都保存下来,而in只会保留重复值的第一个数据。
三、性能分析
假设驱动表A,某列长n,被驱动表B,某列长m。
3.1 in
对于in子查询来说,比较次数为n*m次。
3.2 join
对于join,其实MySQL有三种方式:
优先级Index Nested-LoopJoin > Block Nested-Loop Join > Simple Nested-Loop Join
- Simple Nested-Loop Join:简单嵌套循环连接,n*m次。
- Index Nested-Loop Join:索引嵌套循环连接,n*B表索引的高度。
- Block Nested-Loop Join:缓存块嵌套循环连接,会大大减少内层循环的次数。(默认使用这种算法,默认状态时on)
3.3 小结
所以对于两种方式相比较,肯定是选择join来对SQL做优化呀
这也是一个SQL优化的经典问题,好啦,今天就到这里啦,有问题随机私聊小编~