Oracle中的子查询

子查询其实也是一个完整的查询

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:全部

2.6 子查询中的null :子查询的结果中不要有NULL!!

2.7 一般不在子查询中排序,除非TOP-N问题(分页)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值