美文网首页
Oracle多表连接

Oracle多表连接

作者: weiyu_you | 来源:发表于2018-09-01 16:54 被阅读0次

    永远要相信美好的事情即将发生

    Oracle学习

    多表连接

    1. 内连接
    2. 外连接
    3. 自连接

    笛卡尔集(了解)
    主要是忽略了一个连接条件或者说是一个连接条件失效了,第一张表中的数据和第二张表中的所有数据(行)都有连接,造成数据的交集。开发中,需要避免笛卡尔集

    • 内连接
      两个表(连接)中某 一数据项相等的连接叫内连接。也叫等值连接

      where tb_stu.clazz_id=tb_clazz.id
      

      内连接的运算顺序
      (1)参与的数据表(或连接)中的每列与其它数据表(或连接)的列匹配,会形成一个临时表。
      (2)将满足数据项相等的记录从临时数据表中选择出来。

      select * 
      from scott.dept,scott.emp
      where scott.dept.deptno=scott.emp.deptno
      and scott.emp.ename='SMITH';--20
      

      为了代码简介,我们一般使用别名

      select * from scott.dept d,scott.emp e
      where d.deptno=e.deptno
      and e.ename='SMITH';
      

      内连接的标准写法
      inner join就是一个逗号;
      where 要改成on

      select * from scott.dept d inner join scott.emp e
      on d.deptno=e.deptno
      and e.ename='SMITH';
      
    • 外连接(非等值连接)
      用来查询一张表在另一张表没有关联数据的信息

      外连接的三种方式
      (1)左外连接 left outer join(重点)
      (2)右外连接 right outer join
      (3)全外连接 full outer join

      左外连接
      技巧:如果是左外,就在右边加+
      左边的表会展示出所有的数据,右边表没有对应的数据则显示null

      select * from scott.dept d,scott.emp e
      where d.deptno =e.deptno(+);
      

      左外连接的标准写法

      select * from scott.dept d left outer join scott.emp e
      on d.deptno =e.deptno;
      

      右外连接(参照左外,正好相反)

      select * from scott.dept d, scott.emp e
      where d.deptno(+)=e.deptno;
      

      右外连接的标准写法

      select * from scott.dept d right outer join scott.emp e
      on d.deptno =e.deptn
      

      全外连接

      select * from scott.dept d full outer join scott.emp e
      on d.deptno =e.deptno;
      
    • 自连接(重点)
      在开发中应用比较广泛
      使用自连接时,相当于复制一个镜像出来当另一个表处理,使用自连接可以把一张表当做多张表来使用,获取一些比较特殊的数据。
      使用技巧:可以考虑把它当外键来玩。

      创建一个临时表,数据来自scott.emp

      create table tb_temp as select * from scott.emp  
      

      一个普通员工有自己的经理,经理也是 一个员工,也有自己的经理,查询smith的员工编号,名称,上级经理的编号,上级经理的名称。

      select e1.empno,e1.ename,e1.mgr, e2.ename
      from scott.emp e1,tb_temp e2
      where e1.mgr =e2.empno
      and e1.ename='SMITH';

    相关文章

      网友评论

          本文标题:Oracle多表连接

          本文链接:https://www.haomeiwen.com/subject/mxhuwftx.html