DQL_子查询

子查询

select语句中嵌套select语句,被嵌套的select语句是子查询

子查询可以出现的地方

1
2
3
4
5
6
select
...(select)...
from
...(select)...
where
...(select)...

where子句中使用子查询

案例:找出高于品均薪资的员工信息

1
select * from emp where sal > (select avg(sal) from emp);

from后面嵌套子查询

将查询出来的表作为新的表,当比较的表中有需要做计算的,将计算结果作为新的表

案例:找出每个部门平均薪水的薪资等级

1
2
3
4
5
6
7
8
select
t.*,s.grade
from
(select deptno,avg(sal) as avgsal from emp group by deptno) t
join
salgrade s
on
t.avgsal between s.losal and s.hisal;

案例:找出每个部门平均的薪水等级

1
2
3
4
5
6
7
8
9
10
select
e.deptno,avg(s.grade)
from
emp e
join
salgrade s
on
e.sal between s.losal and s.hisal
group by
e.deptno;

select后面嵌套子查询

案例:找出每个员工所在的部门名称,要求显示员工名和部门名

1
2
3
4
5
6
7
8
select
e.ename,d.dname
from
emp e
join
dept d
on
e.deptno=d.deptno;
1
2
3
4
select
e.ename,(select d.dname from dept d where e.deptno=d.deptno) as dname
from
emp e;