文章目录
子查询其实也是一个完整的查询
1.引例
查出比scott工资高的员工信息:
1.首先我们要查出scott的工资
select sal from emp where ename=‘scott’
2.我们在查出比1中查出的工资工的信息
select * from emp where sal> ;
思考一下,我们是不是可以写成一个语句呢?
其实是可以的,也就是子查询:
SQL> select * from emp where sal >(select sal from emp where ename='SCOTT');
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- -------------------- ------------------ ---------- -------------- ---------- ---------- ----------
7839 KING PRESIDENT 17-11月-81 5000 10
2.子查询可以出现的位置
where ,select ,having, from 不能写在group by 后面
2.1 where
引例就是
2.2 select
单行列(常量列)
在这里插入代码片SQL> select empno 第一列 , ename 第二列 ,(select job from emp where empno = 7369) 第三列 from emp;
第一列 第二列 第三列
---------- -------------------- ------------------
7369 SMITH CLERK
7499 ALLEN CLERK
7521 WARD CLERK
7566 JONES CLERK
7654 MARTIN CLERK
7698 BLAKE CLERK
7782 CLARK CLERK
7788 SCOTT CLERK
7839 KING CLERK
7844 TURNER CLERK
7876 ADAMS CLERK
2.3 having
查询最低工资比10号部门的最低工资高的部门标号
SQL> select deptno ,min(sal) from emp group by deptno having min(sal)>(select min(sal) from emp where deptno=20);
DEPTNO MIN(SAL)
---------- ----------
30 950
10 1300
2.4 主查询和子查询 可以是,也可以不同同一张表
查询销售部的员工信息
1.现根据“销售部”查询 销售部的部门编号30
select deptno from dept where dname = ‘DNAME’ ;
2.根据部门编号30 查询员工信息
select * from emp where deptno = (select deptno from dept where dname = ‘SALES’ );
2.5 子查询可以使用 单行操作符(=,<),多行操作符(in)
查询工资比30号部门中 任意其中一个员工高的(存在) 员工信息
只需要满足一个即可,存在一个就可以 ->any
select *from emp where sal > any(select sal from emp) ;
select *from emp where sal > (select min(sal) from emp) ;
查询工资比30号部门中 全部员工高的(存在) 员工信息
“所有、全部” ** ->all **
select *from emp where sal > all(select sal from emp) ;
select *from emp where sal > (select max(sal) from emp) ;
多行操作符:
查询销售部,财务部的员工信息
select * from emp where deptno in
(select deptno from dept where dname = 'SALES' or dname='ACCOUNTING');
any:只要有一个
all:全部