代码改变世界

Oracle:左外联outer join 与(+) From Itpub.

2011-10-14 15:01  Tracy.  阅读(1352)  评论(0编辑  收藏  举报

们知道,从Oracle9i开始,对于外连接(Outer join)Oracle支持SQL92标准:这个标准有很多新的连接语法,当然不仅是外连接了,这里,我主要讨论的是外连接的新语法:Left Outer Join和Right Outer Join,Full Outer Join这里不会讨论,我会额外总结所有的SQL92新的连接语法。对于接触Oracle比较早的开发人员或DBA来说,外连接用+号已经很习惯了,但是新语法有很多好的优点,Oracle也强烈建议9i以及之后的版本使用新的外连接语法。OK,下面进入正题,那么外连接的新旧语法之间有什么差异呢?请看

DINGJUN123>drop table a;
表已删除。

DINGJUN123>drop table b;
表已删除。

DINGJUN123>drop table c;
表已删除。

DINGJUN123>create table a as
 2 select level id,'x'||level name
 3 from dual connect by level<5
 4 union all
 5 select level,'y'||level
 6 from dual connect by level<5;
表已创建。


DINGJUN123>create table b as
 2 select level id,'x'||level name
 3 from dual connect by level<3;
表已创建。

DINGJUN123>create table c as
 2 select level id,'y'||level name
 3 from dual connect by level<3;
表已创建。

DINGJUN123>select * from a;
 ID NAME
---------- --------------------
1 x1
 2 x2
 3 x3
 4 x4
 1 y1
 2 y2
 3 y3
 4 y4
已选择8行。

DINGJUN123>select * from b;
 ID NAME
---------- --------------------
1 x1
 2 x2
已选择2行。

DINGJUN123>select * from c;
 ID NAME
---------- --------------------
1 y1
 2 y2
已选择2行。


DINGJUN123>set null null


------------------------------test1: outer-join use old syntax--------------------------
DINGJUN123>select *
 2 from a,b
 3 where a.id = b.id(+) and a.name like 'x%';
 ID NAME ID NAME
---------- -------------------- ---------- --------------------
1 x1 1 x1
 2 x2 2 x2
 3 x3 null null
 4 x4 null null
已选择4行。


-------------------------------test2: outer-join use new syntax--------------------------
--NO.1: only use 'on' clause,not 'where' clause

DINGJUN123>select *
 2 from a left join b
 3 on a.id =b.id and a.name like 'x%';
 ID NAME ID NAME
---------- -------------------- ---------- --------------------
1 x1 1 x1
 2 x2 2 x2
 3 x3 null null
 4 x4 null null
 1 y1 null null
 2 y2 null null
 3 y3 null null
 4 y4 null null
已选择8行。


--NO.2:use 'on' and 'where' clause

DINGJUN123>select *
 2 from a left join b
 3 on a.id =b.id
 4 where a.name like 'x%';
 ID NAME ID NAME
---------- -------------------- ---------- --------------------
1 x1 1 x1
 2 x2 2 x2
 4 x4 null null
 3 x3 null null
已选择4行。


DINGJUN123>select *
 2 from a left join b
 3 on a.name like 'x%'
 4 where a.id=b.id;
 ID NAME ID NAME
---------- -------------------- ---------- --------------------
1 x1 1 x1
 2 x2 2 x2
已选择2行。

--Questions: what can you conclude from these analytics?
--something else? please wait.......

ps:

select a.*,b.*
  from a left join b
  on a.id =b.id and a.name like 'x%';

这句话用(+)号怎么写呢?

Newkid告诉我们:

select * from a,b
where a.id=b.id(+)
AND "A"."NAME"=CASE WHEN ("B"."ID"(+) IS NOT NULL) THEN 'a' ELSE 'a' END;