子查询分类:
l 条件子查询
l from子查询
l 查询字段列表中的子查询
一、条件子查询
查询结果,作为另一个查询的过滤条件
1、分类
l 单值子查询 = <> > <
l 多值子查询
in
> all 大于最大值
> any 大于最小值
l 多列子查询
(a,b) in 子查询
2、例子1
select employee_id,first_name,salary from employees where salary=( select min(salary) from employees ); |
select employee_id,first_name,salary, department_id from employees where (department_id,salary) in( select department_id,max(salary) from employees where department_id is not null group by department_id ); |
二、from子查询
1、分组:
把多行记录根据关键字组合在一起形成新的记录;
而多行函数就是根据这个新的记录进行操作的。使用having来判断Count(id),avg(sal),sum(sal),max(sal),min(sal);
例子:
select manager_id,c from ( select count(*) c,manager_id from employees where manager_id is not null group by manager_id order by c desc limit 1 )t; ---- mysql中,必须起别名 |
2、这是标准的执行顺序
select manager_id
from employees
where manager_id is not null
group by manager_id
having count(*) >4
order by count(*) ;
三、字段列表中的子查询
select a,b,c,(select ...) from ... 把查询结果作为字段