Oracle的多表查询------- 子查询

/*

   语法:

      select * from tab1 where ( 子查询  )

     

       select * from (子查询)

      

   子查询作用:

      1)可以作为另一个查询的条件

      2)可以作为一张表

     

    子查询类型:

      1)单行子查询(子查询返回的结果是一条)

      2)多行子查询(子查询返回的结果是多条)

*/

-- 需求:查询工资比编号7521高的员工

-- 1)查询编号7521的员工工资

select sal from emp where empno = 7521;

 

-- 2) 把上面的查询结果作为一个条件,  查询工资比编号7521高的员工

select *

from emp

where sal > (select sal from emp where empno = 7521);

 

-- 需求:查询出比雇员 7654 的工资高,同时从事和 7788 的工作一样的员工

-- 1)查询雇员 7654 的工资

select sal from emp where empno = 7654;

 

--2)查询7788员工的工作

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);

 

 

-- 需求:要求查询每个部门的最低工资和最低工资的雇员和部门名称

-- 1)查询每个部门的最低工资

select deptno,min(sal) as minsal

from emp

groupby deptno;

 

-- 2)把上面查询结果作为一张表

select *

from emp e,dept d,

(select deptno,min(sal) as minsal

from emp

groupby deptno) dminsal

where dminsal.deptno = d.deptno

and e.sal = dminsal.minsal;

 

 

-- 子查询空值问题

-- 需求:查询不是老板的员工

-- 1)查询所有老板的编号

selectdistinct mgr from emp;

 

-- 2)把上面的查询作为条件

-- 这时发现这个查询查不到数据,因为子查询返回null

-- 注意:子查询一旦返回null值,主查询查询没有结果的

select *

from emp

where empno notin (selectdistinct mgr from emp where mgr isnotnull);

 

-- 非法子查询用法

-- 子查询返回多个结果,但是不能在主查询使用单个条件判断

select *

from emp

where job = (select job from emp);

 

 

select * from emp;

select * from dept;



---=========exists用法

/*

  语法:

     select * from tab1 whereexists (sql查询语句)

    

     sql查询语句:

       1)查询返回结果不为null,那么exists结果为true

       2)查询返回结果为null,那么exists结果为false

*/

-- true

select * from emp whereexists (select * from emp where empno = 7369);

-- 上面语句等价于(恒等)

select * from emp where1=1;

 

-- false

select * from emp whereexists (select * from emp where empno = 88888);

-- 上面语句等价于

select * from emp where1=2;

 

-- 需求:查询有员工的部门

select * from dept d whereexists ( select * from emp e where e.deptno =d.deptno  );

 

 

 

 

 

 

select * from emp;

 

select * from dept;



  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值