Sql中的子查询

子查询返回一行记录
使用单行记录比较运算符: = ,!=/< >,<, < = , > , > =


--子查询分为两种用法
--1.将子查询当作一个条件放在where后面使用
--放在where后面又分为两种情况
--(1).子查询返回一条数据,为当行子查询
--查询薪资最高的员工的信息
select e.*
from emp e
where e.sal = ( select max(sal)from emp e)
--(2).子查询返回多行数据,为多行子查询

--查询出来所有经理的信息
select e.*
from emp e
where e.empno in ( select distinct mgr from emp e)

--查询部门编号为20的所有员工中薪资最高的人
select e.*
from emp e
where e.sal >= all(select e.sal from emp e where e.deptno = 20 )
and e.deptno = 20


--2.将子查询作为一张表,放在from后面使用
--求部门平均薪水的等级
select t01.deptno,t01.vsal, sg.grade
from salgrade sg,
(select e.deptno, avg(e.sal) vsal from emp e group by e.deptno) t01
where t01.vsal between sg.losal and sg.hisal

原文地址:https://www.cnblogs.com/su-chu-zhi-151/p/11191186.html