1.概念:查询的过程需要另一个select语句的结果,此时要用到子查询,为了给主查询(外查询)提供数据而先执行的查询(内查询)叫做子查询。关键字:in,not in,exist,not exist,=,<>等。mysql从4.1开始支持子查询,子查询效率会低于连接查询。表连接可以用子查询代替,反过来不一定成功。
2.例子:查询员工中薪水最高的姓名.
select name,salary from employer where salary=(select MAX(salary) from employer);
查询每个部门平均月薪。
select avg(salary) ,department_id from employer where department_id is not null group by department_id;
查询月薪比平均月薪高的员工姓名。
select name salary from employer where salary>(select avg(salary) from employer);