您的位置:首页 > 其它

【FULL OUTER JOIN】全外连接的union all改写方法

2010-07-06 15:37 176 查看
对于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.第二种写法
思路:“a到b的全外连接”=“a到b的内连接” + “b到a的反连接” + “a到b的反连接”。
sec@ora10g> select *
2 from a, b
3 where a.a = b.a
4 union all
5 select *
6 from a, b
7 where a.a(+) = b.a
8 and a.a is null
9 union all
10 select *
11 from a, b
12 where a.a = b.a(+)
13 and b.a is null
14 /

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

5.第三种写法
思路:“a到b的全外连接”=“b到a的外部连接” + “a到b的反连接”。
sec@ora10g> select *
2 from a, b
3 where a.a(+) = b.a
4 union all
5 select *
6 from a, b
7 where a.a = b.a(+)
8 and b.a is null
9 /

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

6.小结
注意,改写方法中的“union all”也可以修改为“union”,之所以上面改写方法中我们使用union all,原因是出于性能方便的考虑,union all的执行效率远大于union操作。

这里展示的是一种转换思路,可一看了之。

-- The End --
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐