DQL语言学习进阶七(子查询)
一、含义
出现在其他语句内部的select语句,称为子查询或内查询
外面的语句可以是inner,update,delete,select等,一般select作为外面语句较多
外部的查询语句为select语句,称为主查询或外查询
二、分类
1、按子查询出现的位置:
select后面:仅支持标量子查询
from后面:支持表子查询
where后面或having后面:支持标量子查询(单行)/列子查询(多行)/行子查询
exists后面(相关子查询):支持表子查询
2、按结果集的行列数不同:
标量子查询(结果集只有一行一列)
列子查询(结果集只有一列多行)
行子查询(结果集只有一行多列)
表子查询(结果集一般为多行多列)
(一)where后面或having后面
1、标量子查询(单行子查询)
2、列子查询(多行子查询)
3、行子查询(多列多行)
特点:
(1)子查询放在小括号内
(2)子查询一般放在条件的右侧
(3)标量子查询,一般搭配着单行操作符使用:> < >= <= = <>
列子查询,一般搭配着多行操作符使用:in any/some all
(4)子查询的执行优先于主查询执行,主查询的条件用到了子查询的结果
1、标量子查询
例1:谁的工资比Abel高
(1)查询Abel的工资
select salary from employee where last_name = ‘Abel’;
(2)查询员工的信息,满足salary>(1)结果
select*from employee where salary>{select salary from employee where last_name ='Abel'};
例2:返回job_id与141号员工相同,salary比143号员工多的员工姓名,job_id和工资
(1)查询141号员工的job_id
select job_id from employee where employee_id =141
(2)查询141号员工的salary
select salary from employee where employee_id =143
(3)查询员工的姓名,job_id和工资,要求job_id=(1)且salary>(2)
select last_name, job_id, salary from employee where job_id ={select job_id from employee where employee_id =141}and salary >{select salary from employee where employee_id =143};
非法使用标量子查询
2、列子查询(多行子查询)
例1:返回location_id是1400或1700的部门中的所有员工姓名
(1)查询location_id是1400或1700的部门编号
selectdistinct department_id from department where location_id in(1400,1700)
(2)查询员工姓名,要求部门号是(1)列表中的某一个
select last_name from employee where department_id in(selectdistinct department_id from department where location_id in(1400,1700));
3、行子查询(结果一行多列或多行多列)
例:查询员工编号最小且工资最高的员工信息
select*from employee where (employee_id, salary) =(select min(employee_id), max(salary)from employee );
(1)查询最小的员工编号
select min(employee_id)from employee
(2)查询最高工资
select max(salary)from employee
(3)查询员工信息
select*from employee where employee_id =(select min(employee_id)from employee )and salary =(select max(salary)from employee );
(二)select后面
注:仅支持标量子查询
例:查询每个部门的员工个数
select d.*,(selectcount(*)from employee e where e.department_id= d.'department_id')from department d;
(三)from后面
注:将子查询结果充当一张表,要求必须起别名
例:查询每个部门的平均工资的工资等级
(1) 查询每个部门的平均工资
select avg(salary), department_id from employee groupby department_id
(2) 连接(1)的结果集和job_grade表,筛选条件平均工资 between lowest_sal and highest_sal
select ag_dep.*, g.'grade_level'from(select avg(salary), department_id from employee groupby department_id ) ag_dep inner join job_grade g on ag_dep.agbetween lowest_sal and highest_sal;
(四)exists后面(相关子查询)
语法:
exists(完整的查询语句) 结果;
结果为1或0
例:查询有员工的部门名
select department_name from department d where exists(select*from employee e where d,'department_id'= e.'department_id');