一、小表驅(qū)動大表的含義
類似循環(huán)嵌套
for(int i=5;.......)
{
for(int j=1000;......)
{}
}
如果小的循環(huán)在外層,對于數(shù)據(jù)庫連接來說就只連接5次,進行5000次操作,如果1000在外,則需要進行1000次數(shù)據(jù)庫連接,從而浪費資源,增加消耗。這就是為什么要小表驅(qū)動大表。
二、in 和exists 性能對比
- 當(dāng)B表的數(shù)據(jù)集小于A表數(shù)據(jù)集時,用in優(yōu)于exists。
select *from tb_emp_bigdata A where A.deptno in (select B.deptno from tb_dept_bigdata B)
- 當(dāng)A表的數(shù)據(jù)集小于B表的數(shù)據(jù)集時,用exists優(yōu)于in。
select *from tb_dept_bigdata A where A.deptno in(select B.deptno from tb_emp_bigdata B);

圖片.png
- 原理
select * from A where id in (select id from B)
等價于
for select id from B
for select * from A where A.id = B.id
當(dāng)B表的數(shù)據(jù)集必須小于A表的數(shù)據(jù)集時,用in 優(yōu)于exists.
select * from A where exists (select 1 from B where B.id = A.id)
等價于
for select * from A
for select * from B where A.id = B.id
當(dāng)B表的數(shù)據(jù)集必須大于A表的數(shù)據(jù)集時,用exists優(yōu)于in.
三、總結(jié)
in后面跟的是小表,exists后面跟的是大表。
簡記:in小,exists大。
對于exists
select .....from table where exists(subquery);
可以理解為:將主查詢的數(shù)據(jù)放入子查詢中做條件驗證,根據(jù)驗證結(jié)果(true或false)來決定主查詢的數(shù)據(jù)是否得以保留。