MySQL⾼级知识(⼗六)——⼩表驱动⼤表
前⾔:本来⼩表驱动⼤表的知识应该在前⾯就讲解的,但是由于之前并没有学习数据批量插⼊,因此将其放在这⾥。在查询的优化中永远⼩表驱动⼤表。
1.为什么要⼩表驱动⼤表呢
类似循环嵌套
for(int i=5;.......)
{
for(int j=1000;......)
{}
exists子查询}
如果⼩的循环在外层,对于数据库连接来说就只连接5次,进⾏5000次操作,如果1000在外,则需要进⾏1000次数据库连接,从⽽浪费资源,增加消耗。这就是为什么要⼩表驱动⼤表。
2.数据准备
根据中的相应步骤在tb_dept_bigdata表中插⼊100条数据,在tb_emp_bigdata表中插⼊5000条数据。
注:100个部门,5000个员⼯。tb_dept_bigdata(⼩表),tb_emp_bigdata(⼤表)。
3.案例演⽰
①当B表的数据集⼩于A表数据集时,⽤in优于exists。
select*from tb_emp_bigdata A where A.deptno in (select B.deptno from tb_dept_bigdata B)
B表为tb_dept_bigdata:100条数据,A表tb_emp_bigdata:5000条数据。
⽤in的查询时间为:
将上⾯sql转换成exists:
select*from tb_emp_bigdata A where exists(select1from tb_dept_bigdata B where B.deptno=A.deptno);
⽤exists的查询时间:
经对⽐可看到,在B表数据集⼩于A表的时候,⽤in要优于exists,当前的数据集并不⼤,所以查询时间相差并不多。
②当A表的数据集⼩于B表的数据集时,⽤exists优于in。
select*from tb_dept_bigdata A where A.deptno in(select B.deptno from tb_emp_bigdata B);
⽤in的查询时间为:
将上⾯sql转换成exists:
select*from tb_dept_bigdata A where exists(select1from tb_emp_bigdata B where B.deptno=A.deptno);
⽤exists的查询时间:
由于数据量并不是很⼤,因此对⽐并不是难么的强烈。
附上视频的结论截图:
4.总结
下⾯结论都是针对in或exists的。
in后⾯跟的是⼩表,exists后⾯跟的是⼤表。
简记:in⼩,exists⼤。
对于exists
select .....from table where exists(subquery);
可以理解为:将主查询的数据放⼊⼦查询中做条件验证,根据验证结果(true或false)来决定主查询的数据是否得以保留。by Shawn Chen,2018.6.30⽇,下午。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论