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条记录

猜你喜欢

转载自blog.csdn.net/mmake1994/article/details/86231127