开发工具与关键技术: Oracle sql*plus PLSQL Developer
作者:邓婵
撰写时间:2019年 4月 14日
什么是子查询?子查询又是内查询,它又分为单行子查询和多行子查询,单行子查询结果只返回一行,而多行子查询返回多行。在主查询之前一次执行完成还有子查询的结果被主查询(外查询)使用,如果子查询结果为空值子查询不返回任何行
1.单行子查询
例1:查询部门id与141号员工相同,工资比107号员工多的员工姓名,部门和工资
select last_name,department_id,salary from test
where department_id = (select department_id from employees where employee_id = 141)
and salary > (select salary from employees where employee_id = 107)
这里我们先要把141号员工所在的部门找出,然后查询107号员工的工资为4200,再筛选出工资比107号员工高的,结合这些条件查询出来的结果如下图所示:
例2:查询平均工资最低的部门信息和该部门的平均工资
select d.*, (select avg(salary) from employees where department_id = d.department_id)
from departments d
where d.department_id = (select department_id from employees group by department_id
having avg(salary) = (select min(avg(salary))from employees group by department_id ))
首先我们要把所有部门的平均工资给计算出来,然后再筛选出最低平均工资的那个部门,得出的结果如下图:
2.多行子查询
例1:查询和100号部门的员工工资相同的其他部门的员工信息
select last_name,salary,department_id from test
where salary in (select salary from test where department_id =100) and department_id !=100
这里先要查询出100号部门所有的员工工资,再返回和100号部门的员工工资相同的其他员工,但不包括100号部门里面的员工,结果如图下所示:
例2:查询比60号部门任一工资低的员工的员工号、姓名 以及工资
select employee_id, last_name, salary from test
where salary < any(select salary from test where department_id =60) and department_id !=60
这里使用any比较符得出的结果为小于子查询当中的任意一个都行,结果如下图所示:
例3:查询比60号部门所有工资都高的员工的员工号、姓名 以及工资
select employee_id, last_name, salary from test
where salary > all(select salary from test where department_id =60) and department_id !=60
这里使用all比较符得出的结果为大于子查询当中的最大的那一个,就如这个例子,子查询当中最高工资为9000,所以查询出来的结果都必须大于9000,结果如下图所示: