Oracle之子查询(嵌套查询select嵌套)

一、单值子查询(> >=  = < <= <> 子查询的结果为1个数据)

    --查询最高工资的员工信息 
    --1.查询出最高工资 --5000
    select max(sal) from emp;
    --2. 工资等于最高工资
    select * from emp where sal = (select max(sal) from emp);
    --查询出比雇员7654的工资高,同时和7788从事相同工作的员工信息
    --1.雇员7654的工资 1250
    select sal from emp where empno = 7654;
    --2.7788从事的工作 ANALYST
    select job from emp where empno = 7788;
    --3.两个条件合并
    select * from emp where sal > (select sal from emp where empno = 7654) and job = (select job from emp where empno = 7788);
    --查询每个部门最低工资的员工信息和他所在的部门信息
    select e.DEPTNO, min(e.sal) from emp e GROUP by e.DEPTNO;
    select * from emp e1
        inner join (select e.DEPTNO, min(e.sal) minsal from emp e GROUP by e.DEPTNO) t1
            on e1.DEPTNO=t1.DEPTNO and e1.sal=t1.minsal

二、多值子查询(in  not in  any  all  exist 子查询的结果为多个数据)

exist(当做布尔值来处理,当查询语句有结果时,返回true,否则返回false)

    --查询不到数据    
    select * from emp where exists(select * from emp where deptno = 123456);
    --查询emp中所有记录 相对于where后条件永远为true
    select * from emp where exists(select * from emp where deptno = 20); 
    --查询有员工的部门的信息
    select * from dept d1 where exists(select * from emp e1 where e1.deptno = d1.deptno );
    --查询不是领导的信息(含null值正确写法)
    select * from emp where empno not in (select mgr from emp where mgr is not null); --查询出8条记录

  三、子查询中的null值问题(解决方法where ... is not null)

  通常情况下, 数据库中不要出现null,最好的做法加上非空约束Not null,null值并不代表不占空间, char(100) null占100个字符

    --查询不是领导的信息(含null值错误写法)
    select * from emp where empno not in (select mgr from emp); --查询不到记录
    select * from emp where empno <>all(select mgr from emp);--上行等价写法

    --查询不是领导的信息(含null值正确写法)
    select * from emp where empno not in (select mgr from emp where mgr is not null); --查询出8条记录

 

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值