Mysql高級(七) 小表驅(qū)動大表

一、小表驅(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ù)是否得以保留。

參考博客:https://www.cnblogs.com/developer_chan/p/9247185.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容