什么是子查询?
select语句里面嵌套select语句,就叫做子查询
子查询的嵌套位置:
子查询语句可以嵌套在select/from/where后面,下面分别举出三个位置的不同例子:
例1:找出薪水比公司平均薪水高的员工,要求显示员工名和薪水
mysql> select ename,sal from emp where sal>(select avg(sal) from emp); +-------+---------+ | ename | sal | +-------+---------+ | JONES | 2975.00 | | BLAKE | 2850.00 | | CLARK | 2450.00 | | SCOTT | 3000.00 | | KING | 5000.00 | | FORD | 3000.00 | +-------+---------+
例2:找出每个部门的平均薪水,要求显示平均薪水的薪水等级
第一步:先找出每个部门的平均薪水
mysql> select deptno,avg(sal) avgsal from emp group by deptno; +--------+-------------+ | deptno | avgsal | +--------+-------------+ | 10 | 2916.666667 | | 20 | 2175.000000 | | 30 | 1566.666667 | +--------+-------------+
把结果看成一个临时存在的表t
第二步:找出临时表t每个部门平均薪水的薪水等级
mysql> select t.deptno,t.avgsal,s.grade from (select deptno,avg(sal) avgsal from emp group by deptno) t join salgrade s on t.avgsal between s.losal and s.hisal; +--------+-------------+-------+ | deptno | avgsal | grade | +--------+-------------+-------+ | 10 | 2916.666667 | 4 | | 20 | 2175.000000 | 4 | | 30 | 1566.666667 | 3 | +--------+-------------+-------+
例3:首先忽略括号里面的子句,select e.ename from emp e,即找出员工名,再看括号里面,可以得出,结果是找出员工名即其对应的单位名