1.為什麼要小表驅動大表呢
類似循環嵌套
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的查詢時間為:
經對比可看到,在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)來決定主查詢的數據是否得以保留。
閱讀更多 程序界小哥 的文章