子查询
子查询实例展示:
1.如何查的所有比“CLARK”工资高的员工的信息?
select * from emp where sal > ( select sal from emp where ename = 'CLARK' );
2. 如何查询工资高于平均工资的员工的姓名和工资?
select ename, sal from emp where sal > ( select avg(sal) from emp );
3. 思考:查询scott同一个部门并且比他工资低的员工的名字和工资?
SELECT ENAME,SAL FROM EMP WHERE SAL<=(select sal from emp where ename = 'SCOTT') AND DEPTNO = (SELECT DEPTNO FROM EMP WHERE ENAME='SCOTT' );
单行子查询:
4. 如何查询职务和scott相同,比scott雇佣时间早的员工信息
select * from emp where job = (select job from emp where ename ='SCOTT') AND hiredate < (select hiredate from emp where ename ='SCOTT' );
5. 如何查询工资比scott高或者雇佣时间比scott早的员工姓名和编号
select empno,ename from emp where sal>(select sal from emp where ename ='SCOTT') or hiredate < (select hiredate from emp where ename ='SCOTT' );
多行子查询
6. 查询工资比所有的 SALESMAN 都高的员工编号,名字,工资
select empno,ename,sal from emp where sal>ALL(select sal from emp where job ='SALESMAN');
7. 查询部门20中职务同部门10的员工一样的员工信息
select * from emp where deptno = 20 and job = ANY(select job from emp where deptno=10);
8. 查询员工中有哪些是领导
select * from emp where empno in (select distinct mgr from emp where mgr is not null);
9. 查询每个部门平均薪水的等级
select t.deptno,t.avg_sal,s.grade from (select deptno,avg(sal) avg_sal from emp group by deptno) T --把查询的结果看作是一个表 ,salgrade s where t.avg_sal between s.losal and s.hisal; --将子查询作为一张表,实现多表连接查询