子查询指一个查询语句嵌套在另一个查询语句内部的查询
select ename, mname
from (select e.*, d.empno, d.ename mname, d.job, d.sal, d.deptno from emp e, emp d where e.mgr = d.empno(+));
(1)单行子查询
单行子查询:子查询的sql语句只查出一条记录
–查询工资大于10号部门平均工资的员工信息
select * from emp where sal>(select avg(sal) from emp where deptno=10);
(2)多行子查询
多行子查询:子查询的sql语句查出若干条记录
in、not in、exists、not exists、all、any
**1)用单行子查询
–查询20号部门的最高工资
select max(sal) from emp where deptno=20;
select * from emp where sal>( select max(sal) from emp where deptno=20);
2)>all
–20号部门的员工工资是一个集合
select sal from emp where deptno=20;
select * from emp where sal>all(select sal from emp where deptno=20);
3.exists、not exists
exists:后面跟子查询,如果子查询能查出数据,那么条件是真的,如果子查询查不出结果,条件不成立
select * from dept d where exists(select * from emp where deptno=d.deptno);
–查询没有有员工的部门信息
select * from dept d where not exists(select * from emp where deptno=d.deptno);
4.having后面的子查询
–查询各个部门的部门编号和员工人数,要求部门的平均工资大于30号部门的平均工资
select deptno,count(*),avg(sal) from emp group by deptno having avg(sal)>1500;
–查询30号部门的平均工资
select avg(sal) from emp where deptno=30;
select deptno,count(*) from emp group by deptno having avg(sal)>(select avg(sal) from emp where deptno=30);
5.select 和from 之间的子查询
select empno,ename,(select 1 from dual) from emp;
注意:select 和from之间的子查询,子查询的结果只能是单行单列
原始排序:
select e.,(select count() from emp where sal>e.sal) from emp e order by 9;