1. 子查询所要解决的问题:不能一步求解
2.注意的问题
2.1where,select,having,from使用子查询
--select select empno,sal,(select job from emp where empno =7389) 第四列 from emp; --having,聚合函数用having select deptno,min(sal) from emp group by deptno having min(sal)> (select min(sal) from emp where deptno =10) --from select * from (select empno,ename,sal from emp)
2.2 不可以在group by 后面使用子查询
2.3 sql 优化:尽量使用多表查询
--查询部门名称是sales 的员工
--子查询(访问数据库2次) select * from emp where deptno = (select deptno from dept where dname='SALES') --多表查询(访问数据库1次) select e.* from emp e,dept d where e.deptno =d.deptno and d.dname ='SALES'
2.4一般不再子查询中排序;但在top-n 分析问题中,必须对子查询排序
oracle 10g 当中没有top关键字
2.5一般先执行子查询,在执行主查询;但相关子查询例外
2.6 多行子查询:in,any(大于集合当中最小值),all(大于集合当中最大值)
--in 在集合中,查询部门名称为sales和accounting员工 select * from emp where deptno in(select deptno from dept where dname='SALES' or dname='ACCOUNTING');
--any 和集合中任意一个值进行比较(最小值) --查询工资比30号部门任意一个员工高的员工信息 select * from emp where sal> any (select sal from emp where deptno=30);
--all所有值进行比较,比30号部门员工所有的员工高的员工信息 select * from emp where sal > all (select sal from emp where deptno=30) ==== select * from emp where sal > (select max(sal) from emp where deptno=30)
2.7 多行子查询中的null
--not in --分析:主体还是查询员工,含有mgr 这一列的才是老板的员工,not in 当中只能查询不包含null的 --查询不是老板的员工 select * from emp where empnoo not in (select mgr from emp where mgr is not null); --查询是老板的员工 select * from emp where empnoo in (select mgr from emp);