子查询
1、子查询概念:当一个查询的结果是另一个查询的条件时,称之为子查询。
2、使用子查询的注意事项:子查询可以嵌套多层,子查询需要圆括号()括起来。
3、单行子查询操作符有:=、>、>=、<、<=、<>
案例:
//查询编号7876相同职位的员工信息 并且薪资大于编号为7521的薪资的员工信息
SQL> select * from emp where job=( select job from emp where empno=7876) and sal>( select sal from emp where empno=7521);
//子查询含有组函数
SQL> select * from emp where sal>(select avg(nvl(sal,0)) from emp);
//子查询含有having子句 查询部门的最小工资大于20号部门最小工资的部门号及最小工资数
SQL> select deptno,min(sal) from emp group by deptno having min(sal)>( select min(sal) from emp where deptno=20);
备注:子查询可以返回空行 没要查询到结果是可以的。
4、子查询(内查询)在主查询之前一次执行完成。
子查询的结果被主查询使用(外查询)。
案例:
查询员工的工资大于JONES的员工信息
分析过程如下:
首先:查询JONES的员工工资是多少 :结果2975
SQL> select sal from emp where ename='JONES';
实际上我们要查询的是:薪资大于2975的员工的信息写法如下:
SQL> select * from emp where sal>2975;
//综合以上写出子查询的结果如下:
SQL> select * from emp where sal>(select sal from emp where ename='JONES');
注意:
子查询要包含在括号内。
将子查询放在比较条件的右侧。
5、多行子查询
案例:
//查询薪水小于工作岗位CLERK的任何一个薪资的员工信息 并且不包含工作岗位为CLERK的员工信息
SQL> select * from emp where sal < any (select sal from emp where job='CLERK') and job<>'CLERK';
//all与所有值比较 >all 代表的是大于查询结果的最大值
SQL> select * from emp where sal > all (select sal from emp where job='CLERK') and job<>'CLERK';
//查询岗位与部门编号为10相同的员工信息 不包含自己。
SQL> select * from emp where job in(select job from emp where deptno=10) and deptno<>10;