1.為什么要小表驅(qū)動大表呢
類似循環(huán)嵌套
for(int i=5;.......)
{
for(int j=1000;......)
{}
}
如果小的循環(huán)在外層,對于數(shù)據(jù)庫連接來說就只連接5次,進(jìn)行5000次操作,如果1000在外,則需要進(jìn)行1000次數(shù)據(jù)庫連接,從而浪費(fèi)資源,增加消耗。這就是為什么要小表驅(qū)動大表。
比如:我們在tb_dept_bigdata表中插入100條數(shù)據(jù),在tb_emp_bigdata表中插入5000條數(shù)據(jù)。
注:100個部門,5000個員工。tb_dept_bigdata(小表),tb_emp_bigdata(大表)。
①當(dāng)B表的數(shù)據(jù)集小于A表數(shù)據(jù)集時,用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條數(shù)據(jù),A表tb_emp_bigdata:5000條數(shù)據(jù)。
用in的查詢時間為:
經(jīng)對比可看到,在B表數(shù)據(jù)集小于A表的時候,用in要由于exists,當(dāng)前的數(shù)據(jù)集并不大,所以查詢時間相差并不多。
②當(dāng)A表的數(shù)據(jù)集小于B表的數(shù)據(jù)集時,用exists由于in。
select *from tb_dept_bigdata A where A.deptno in(select B.deptno from tb_emp_bigdata B);
用in的查詢時間為:
將上面sql轉(zhuǎn)換成exists:
select *from tb_dept_bigdata A where exists(select 1 from tb_emp_bigdata B where B.deptno=A.deptno);
用exists的查詢時間:
由于數(shù)據(jù)量并不是很大,因此對比并不是難么的強(qiáng)烈。
附上結(jié)論截圖:
.總結(jié)
下面結(jié)論都是針對in或exists的。
in后面跟的是小表,exists后面跟的是大表。
簡記:in小,exists大。
對于exists
select .....from table where exists(subquery);
可以理解為:將主查詢的數(shù)據(jù)放入子查詢中做條件驗(yàn)證,根據(jù)驗(yàn)證結(jié)果(true或false)來決定主查詢的數(shù)據(jù)是否得以保留。






