含义:一个select语句中包含另一个或多个完整的select语句。
1.标量子查询:返回的结果是一个数据(单行单列),一般出现在select、where、having、join和from子句中。
例:查询基本工资高于公司平均工资的员工信息
select *from emp where sal>avg(sal);-- 报错where子句中不能聚合函数
用标量子查询:
(1)查询公司平均工资
select avg(sal) from emp;
(2)将子查询运用到where子句中,替换聚合函数
select * from emp where sal>( select avg(sal) from emp);
子查询的效率不高,当where子句中需要聚合函数作为筛选条件,不能直接使用再使用子查询.
2.行子查询:返回的结果是一行(单行多列),一般出现在where、having、from和join子句中。
例:查询和smith同部门同职位的员工:empno,ename,job,deptno
(1)查询smith所在的部门和职位
select deptno,job from emp where ename=’smith’;
(2)将查询结果与where子句结合
select empno,ename,job,deptno from emp
where (deptno,job)=( select deptno,job from emp where ename=’smith’)
and ename<>’smith’;
3. 列子查询:返回结果是一列(多列单行),一般出现在select、where、having、from和join子句中。
例:查询普通员工的工资等级:empno,ename,sal,grade
(1)查询出那些是普通员工
select mgr from emp;-- 因为mgr列中存在空值,对后续的查询产生影响将其剔除
select mgr from emp where mgr is not null;
(2)与where子句结合查询出普通员工
select empno,ename,sal,grade from emp left join salgrade
on sal between hisal and losal
where empid not in (select mgr from emp where mgr is not null);
4.表子查询:返回的结果是一张表(多行多列),一般出现在where、having、from和join子句中,必须添加表别名,其中如果需要引用表子查询中的计算字段,必须添加列别名才可以引用。
例:查询各部门最高工资的员工:empno,ename,sal,deptno
(1)每个部门最高工资,再查出最高工资的员工
select deptno,max(sal) from emp group by deptno;
(2)与join子句结合查出各部门最高工资的员工
select empid,ename,sal,emp.deptno
from emp
left join (select deptno,max(sal) as 最高工资 from emp group by deptno) as t
on emp.deptno=t.deptno
where sal=最高工资;