小表驱动大表

一、为什么要小表驱动大表

类似循环嵌套。

for(int i=5;.......)
{
     for(int j=1000;......)
     {}
}

如果小的循环在外层,对于数据库连接来说就只连接5次,进行5000次操作,如果1000在外,则需要进行1000次数据库连接,从而浪费资源,增加消耗。这就是为什么要小表驱动大表。

二、数据准备

在tb_dept_bigdata表中插入100条数据,在tb_emp_bigdata表中插入5000条数据。

注: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条数据。

用in的查询时间为:

将上面sql转换成exists:

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)来决定主查询的数据是否得以保留

 

转自:https://www.cnblogs.com/developer_chan/p/9247185.html

posted @ 2020-09-19 21:53  codedot  阅读(219)  评论(0编辑  收藏  举报