小表驱动大表:
写sql前确定几件事:
以员工(emp)和部门(dept)为例
1、谁在外(左),谁在里(右)(根据中文描述来判断)
找出指定部门里的员工:员工在外(左),部门在里(右)
找出有员工参加的部门:部门在外(左),员工在里(右)
2、谁大谁小(根据数据量)
当小表在里时,使用in
当大表在里时,使用exists
正解:
select * from tb_emp A where A.deptno in (select B.deptno from tb_dept B)
//select * from A where A.id in (select id from B);
select * from tb_dept A where exists (select 1 from tb_emp B where A.id=B.deptno)
//select ... from table where exists (subquery) 将主查询到的数据,放进子查询中做条件验证,根据结果(true/false)来决定主查询的数据是否得以保留
//subquery: select 1或*或'X'或任何常量 from B where A.id=B.id);
下面结论都是针对in或exists的。
in后面跟的是小表,exists后面跟的是大表。
简记:in小,exists大。
对于exists
select .....from table where exists(subquery);
可以理解为:将主查询的数据放入子查询中做条件验证,根据验证结果(true或false)来决定主查询的数据是否得以保留。