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)來決定主查詢的數據是否得以保留。