全外连接的union改写方法

来源:互联网 发布:windows to go有什么用 编辑:程序博客网 时间:2024/05/16 15:45

对于SQL中的连接操作在实现业务需求的时候比较方便和高效,这里针对“全外连接”展示一下在Oracle中的两种写法。
每种写法因人而异,以达到实验需求为目的。

有关内连接,左连接和右连接的简单演示请参考:《【实验】内连接,左连接,右连接,全外连接》http://space.itpub.net/519536/viewspace-563019

1.创建实验表并初始化实验数据
SQL> create table a (a number(1),b number(1),c number(1));
SQL> create table b (a number(1),d number(1),e number(1));
SQL> insert into a values(1,1,1);
SQL> insert into a values(2,2,2);
SQL> insert into a values(3,3,3);
SQL> insert into b values(1,4,4);
SQL> insert into b values(2,5,5);
SQL> insert into b values(4,6,6);
SQL> commit;

2.查看一下初始化数据内容
sec@ora10g> select * from a;

         A          B          C
---------- ---------- ----------
         1          1          1
         2          2          2
         3          3          3

sec@ora10g> select * from b;

         A          D          E
---------- ---------- ----------
         1          4          4
         2          5          5
         4          6          6

3.第一种写法,这也是标准SQL的写法。功能明确,不过理解有点小障碍。
sec@ora10g> select * from a full outer join b on a.a = b.a;

         A          B          C          A          D          E
---------- ---------- ---------- ---------- ---------- ----------
         1          1          1          1          4          4
         2          2          2          2          5          5
         3          3          3
                                          4          6          6

4.第二种写法,思路是:全外连接就是左外连接和右外连接数据集合的并集。因此将左外连接和右外连接union后变得到我们的最终结果
sec@ora10g> select * from a, b where a.a = b.a(+)
  2  union
  3  select * from a, b where a.a(+) = b.a
  4  /

         A          B          C          A          D          E
---------- ---------- ---------- ---------- ---------- ----------
         1          1          1          1          4          4
         2          2          2          2          5          5
         3          3          3
                                          4          6          6

5.注意
注意比较两种写法对于不同数据集合的结果。

本篇文章来源于 新世纪网安基地 (www.520hack.com) 原文出处:http://www.520hack.com/Article/Text7/wgfile/200911/16454.html

原创粉丝点击