Oracle左连接,右连接,全外连接和+号的用法

左外连接  left outer join/left join

LEFT JOIN是以左表的记录为基础的,示例中t_A可以看成左表,t_B可以看成右表,它的结果集是t_A表中的全部数据,再加上t_A表和t_B表匹配后的数据。换句话说,左表(t_A)的记录将会全部表示出来,而右表(t_B)只会显示符合搜索条件的记录。t_B表记录不足的地方均为NULL。

示例:select * from t_A a left join t_B b on a.id = b.id; 或 select * from t_A a left outer join t_B b on a.id = b.id;

test:

SELECT S.S#,SN,C#,G
from S left join SC
on S.S#=SC.S#;

       S#    SN    C#    G
1    S1     A                  C2                 A    
2    S1     A                  C1                 A    
3    S2     B                  C2                 C    
4    S2     B                  C4                 C    
5    S2     B                  C1                 B    
6    S3     C                      
7    S4     D                     

 

用(+)来实现, 这个+号可以这样来理解: + 表示补充,即哪个表有加号,这个表就是匹配表。如果加号写在右表,左表就是全部显示,所以是左连接。

select S.S#,SN,C#,G

from S,SC

where S.S#=SC.S#(+);

       S#    SN    C#    G
1    S1     A                  C2                 A    
2    S1     A                  C1                 A    
3    S2     B                  C2                 C    
4    S2     B                  C4                 C    
5    S2     B                  C1                 B    
6    S3     C                      
7    S4     D                     

 

右外连接  right outer join/right join

和LEFT JOIN的结果刚好相反,是以右表(t_B)为基础的。它的结果集是t_B表所有记录,再加上t_A和t_B匹配后的数据。 t_A表记录不足的地方均为NULL。

示例:select * from t_A a right join t_B b on a.id = b.id;
或
select * from t_A a right outer join t_B b on a.id = b.id;

test:

select S.S#,SN,C#,G
from S right join SC
on S.S#=SC.S#;

       S#    SN    C#    G
1    S1     A                  C2                 A    
2    S1     A                  C1                 A    
3    S2     B                  C4                 C    
4    S2     B                  C2                 C    
5    S2     B                  C1                 B   

用(+)来实现, 这个+号可以这样来理解: + 表示补充,即哪个表有加号,这个表就是匹配表。如果加号写在左表,右表就是全部显示,所以是右连接

test:

select S.S#,SN,C#,G
from S,SC
where S.S#(+)=SC.S#;

       S#    SN    C#    G
1    S1     A                  C2                 A    
2    S1     A                  C1                 A    
3    S2     B                  C4                 C    
4    S2     B                  C2                 C    
5    S2     B                  C1                 B   

全外连接  full outer join/full join

左表和右表都不做限制,所有的记录都显示,两表不足的地方均为NULL。 全外连接不支持(+)写法。

示例: select * from t_A a full join t_B b on a.id = b.id; 或 select * from t_A a full outer join t_B b on a.id = b.id;

posted on 2017-11-21 15:54  John_Baker  阅读(1165)  评论(0编辑  收藏  举报