前言:原本小表驱动大表的知识应该在前面就讲解的,可是因为以前并无学习数据批量插入,所以将其放在这里。在查询的优化中永远小表驱动大表。html
相似循环嵌套sql
for(int i=5;.......) { for(int j=1000;......) {} }
若是小的循环在外层,对于数据库链接来讲就只链接5次,进行5000次操做,若是1000在外,则须要进行1000次数据库链接,从而浪费资源,增长消耗。这就是为何要小表驱动大表。数据库
根据MySQL高级知识(十)——批量插入数据脚本中的相应步骤在tb_dept_bigdata表中插入100条数据,在tb_emp_bigdata表中插入5000条数据。windows
注:100个部门,5000个员工。tb_dept_bigdata(小表),tb_emp_bigdata(大表)。学习
①当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条数据。spa
用in的查询时间为:3d
将上面sql转换成exists:code
select *from tb_emp_bigdata A where exists(select 1 from 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(select 1 from tb_emp_bigdata B where B.deptno=A.deptno);
用exists的查询时间:
因为数据量并非很大,所以对比并非难么的强烈。
附上视频的结论截图:
下面结论都是针对in或exists的。
in后面跟的是小表,exists后面跟的是大表。
简记:in小,exists大。
对于exists
select .....from table where exists(subquery);
能够理解为:将主查询的数据放入子查询中作条件验证,根据验证结果(true或false)来决定主查询的数据是否得以保留。
by Shawn Chen,2018.6.30日,下午。