SQL的子查询
子查询的理解:查询 (内查询) 在主查询之前一次执行完成。子查询的结果被主查询(外查询)使用。
子查询要包含在括号内。 将子查询放在比较条件的右侧。 单行操作符对应单行子查询,多行操作符对应多行子查询。
单行子查询:只返回一行。使用单行比较操作符。
(单行比较操作符有: =, >, <> ,!= 等)
子查询的having字句:可以使用组函数
首先执行子查询。 向主查询中的having 子句返回结果。
多行子查询:返回多行语句,使用多行比较运算符。
(多行比较运算符:in any all)
in 等于返回结果中的任意一个
any 和返回结果的某一个值比较
all 和返回结果的所有值比较
背景:
–谁的工资比 Abel高?
–方法一:
–1)步骤一
select salary
from employees
where lower(last_name) = ‘abel’;
–2)步骤二
select last_name,salary
from employees
where salary > 11000;
–方法二:子查询 外查询
select last_name,salary
from employees
where salary > (
select salary
from employees
where lower(last_name) = 'abel'
);
–查询last_name 为’Chen’的员工的manager的信息
方法一 子查询
select employee_id,last_name,salary
from employees
where employee_id = (
select manager_id
from employees
where last_name = 'Chen'
);
方法二:
select mgr.employee_id,mgr.last_name,mgr.salary
from employees emp,employees mgr
where emp.manager_id = mgr.employee_id
and emp.last_name = ‘Chen’;
–43*. 查询平均工资最低的部门信息和该部门的平均工资
select d.*,(select avg(salary) from employees where department_id = d.department_id)
from departments d
where d.department_id = (
–2)找到最低的平均工资的部门id
select department_id
from employees
having avg(salary) = (
–1)查询出各个部门中的最低的平均工资
select min(avg(salary))
from employees
group by department_id)
group by department_id)