1.為什么要小表驅(qū)動(dòng)大表呢
類似循環(huán)嵌套
for(int i=5;.......)
{
for(int j=1000;......)
{}
}
如果小的循環(huán)在外層,對(duì)于數(shù)據(jù)庫(kù)連接來(lái)說(shuō)就只連接5次靶溜,進(jìn)行5000次操作开瞭,如果1000在外,則需要進(jìn)行1000次數(shù)據(jù)庫(kù)連接罩息,從而浪費(fèi)資源嗤详,增加消耗。這就是為什么要小表驅(qū)動(dòng)大表瓷炮。
2.數(shù)據(jù)準(zhǔn)備
在tb_dept_bigdata表中插入100條數(shù)據(jù)葱色,在tb_emp_bigdata表中插入5000條數(shù)據(jù)。
注:100個(gè)部門崭别,5000個(gè)員工冬筒。tb_dept_bigdata(小表),tb_emp_bigdata(大表)茅主。
3.案例演示
①當(dāng)B表的數(shù)據(jù)集小于A表數(shù)據(jù)集時(shí)舞痰,用in優(yōu)于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的查詢時(shí)間為:
將上面sql轉(zhuǎn)換成exists:
select *from tb_emp_bigdata A where exists(select 1 from tb_dept_bigdata B where B.deptno=A.deptno);
用exists的查詢時(shí)間:
經(jīng)對(duì)比可看到,在B表數(shù)據(jù)集小于A表的時(shí)候赫段,用in要優(yōu)于exists呀打,當(dāng)前的數(shù)據(jù)集并不大,所以查詢時(shí)間相差并不多糯笙。
②當(dāng)A表的數(shù)據(jù)集小于B表的數(shù)據(jù)集時(shí)贬丛,用exists優(yōu)于in。
select *from tb_dept_bigdata A where A.deptno in(select B.deptno from tb_emp_bigdata B);
用in的查詢時(shí)間為:
將上面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í)間:
由于數(shù)據(jù)量并不是很大给涕,因此對(duì)比并不是難么的強(qiáng)烈豺憔。
附上視頻的結(jié)論截圖:
4.總結(jié)
下面結(jié)論都是針對(duì)in或exists的。
in后面跟的是小表够庙,exists后面跟的是大表恭应。
簡(jiǎn)記:in小,exists大耘眨。
對(duì)于exists
select .....from table where exists(subquery);
可以理解為:將主查詢的數(shù)據(jù)放入子查詢中做條件驗(yàn)證昼榛,根據(jù)驗(yàn)證結(jié)果(true或false)來(lái)決定主查詢的數(shù)據(jù)是否得以保留。