子查询
- 一个查询语句,嵌套在另一个查询语句内部;
- 子查询先执行,其结果被外层主查询使用;
- 子查询放入括号内;
- 子查询放在比较条件的右侧;
- 子查询返回一条,为单行子查询(对应单行操作符= != > < …);返回多条,则为多行子查询;
- 子查询执行次数不受外层查询的影响,则为不相关子查询;
# 工资高于abel的人
select name, salary from employees where salary >
(select salary from employees where name='abel');
内部子查询仅仅执行一次, 故为不相关;
子查询案例
- 单行子查询
- 查询最低工资大于 50号 部门最低工资的部门的id和最低工资;
# 由内而外解析# 50号 部门最低工资
select min(salary) from employees where depart_id=50;# 查询最低工资大于()的部门的id和最低工资
select depart_id, min(salary) from employees group by depart_id having min(salary) > ();# 将以上子查询放入()中即可;
- 查询员工的employee_id, name, location; 若员工的部门id与 (loc_id=190)的员工部门id相同,则location值为A ,否则为B;
select employee_id, name, (case depart_id when (select depart_id from employees where loc_id=190) then 'A'else 'B' end) as location from employees;
- 多行子查询
- 子查询返回多行;
- 使用多行操作符
- in 在返回的结果集合中;
- any 和结果集合中一个比较;
- all 和结果集合中的所有 比较;
- some,即any
# 薪资小于任何一个结果
select xxx from employees where salary < any(多行子查询);# 查询 平均工资 最低的部门
select depart_id, min(avg_salary) from (select depart_id, avg(salary) as avg_salary from employees group by depart_id) as tt;select depart_id from employees group by depart_id having avg(salary) <= all(select avg(salary) as avg_salary from employees group by depart_id)