Oracle数据库的查询之子查询(六)
一.明确什么是子查询当一个查询是另一个查询的条件时,称之为子查询 二.什么时候使用子查询在问题不能一步求解出来的时候使用. 例如:查询谁的工资比SCOTT的高
select ename from emp where sal > (select sal from emp where ename = 'SCOTT');
子查询注意的10个问题:(1)子查询语法中的小括号 三.子查询在操作中有三类:单列子查询:返回的结果是一列的一个内容 四.单行子查询 1.查询出比雇员7654的工资高,同时从事和7788的工作一样的员工
分析:先查询出雇员7654的工资
select sal from emp where empno = 7654;
再查询出7788员工的工作
select job from emp where empno = 7788;
然后再整合在一起
select * from emp e where e.sal >(select e1.sal from emp e1 where e1.empno = 7654) and e.job = (select e2.job from emp e2 where e2.empno = 7788);
结果为: 2.要求查询每个部门的最低工资和最低工资的雇员和部门名称
分析:先查询出每一个部门的最低工资
select deptno,min(sal) minsal from emp group by deptno ;
通过部门号和最低工资可以找到雇员的名字,然后整合在一起
select d.dname,a.minsal,e.ename from dept d,( select deptno,min(sal) minsal from emp group by deptno ) a,emp e where d.deptno = a.deptno and e.sal = a.minsal;
在返回多条记录的子查询可以把它的结果集当做一张表,给这张表起个别名,如上面的a 五.多行子查询 1.在多行子查询中使用in操作符 1.查询出每个部门最低工资的员工
select * from emp e where e.sal in (select min(sal) from emp group by deptno);
1.查询工资比30号部门任意一个员工高的员工信息
select * from emp e where e.sal > any (select e1.sal from emp e1 where e1.deptno = 30);
1.查询工资比30号部门所有员工高的员工信息
select * from emp e where e.sal > all (select e1.sal from emp e1 where e1.deptno = 30);
1.找到员工表中薪水大于本部门平均薪水的员工
分析:将主查询中的部门号传递到子查询中
select empno,ename,sal,(select avg(sal) from emp where deptno = e.deptno) avgsal from emp e where sal > (select avg(sal) from emp where deptno = e.deptno); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |