`
xq30397022
  • 浏览: 13030 次
  • 性别: Icon_minigender_1
  • 来自: 天津
文章分类
社区版块
存档分类
最新评论

DB2sql中的内外连接

 
阅读更多
有表t1,t2

t1:
C1 C2 C3
-- ---------- --
1rick B0
2smith C0
3john E0

3 条记录已选择。
t2:
C1 C2
-- ----------
A0 sale DEPT
B0 prod DEPT
C0 cout DEPT
D0 mage DEPT

4 条记录已选择。

1.db2的内连接
下面是内连接,内连接和普通的where子句,输出相同,即在两表共有的行才会输出,即也可以用:select * from t1,t2 where t1.c3=t2.c1
内连接没有左右之分.

db2 => select * from t1 inner join t2 on t1.c3=t2.c1

C1 C2 C3 C1 C2
-- ---------- -- -- ----------
1rick B0 B0 prod DEPT
2smith C0 C0 cout DEPT

2 条记录已选择。


2.db2的外连接:外连接分左外连接右外连接,下面我们看看他们的区别:

db2 => select * from t1 left outer join t2 on t1.c3=t2.c1

C1 C2 C3 C1 C2
-- ---------- -- -- ----------
1rick B0 B0 prod DEPT
2smith C0 C0 cout DEPT
3john E0 --

3 条记录已选择。
左连接保留前面表的所有记录,后表中没有的补null.



db2 => select * from t1 right outer join t2 on t1.c3=t2.c1

C1 C2 C3 C1 C2
-- ---------- -- -- ----------
-- -A0 sale DEPT
1rick B0 B0 prod DEPT
2smith C0 C0 cout DEPT
-- -D0 mage DEPT

4 条记录已选择。
左连接保留后表的所有记录,前表中没有的补null.
我们可以把右连接,的表的顺序颠倒一下,并写成左外连接,其结果应该是一样的.
在DB2的内部机制中,会把右外连接重写成左外连接.故我们在写sql语句时尽量使用左外连接.


3.全外连接.
db2 => select * from t1 full outer join t2 on t1.c3=t2.c1
C1 C2 C3 C1 C2
-- ---------- -- -- ----------
-- -A0 sale DEPT
1rick B0 B0 prod DEPT
2smith C0 C0 cout DEPT
-- -D0 mage DEPT
3john E0 --

5 条记录已选择。
全外连接会输出两表的所有的数据,包括内连接和左外连接和右外连接的行.


4.与sybase的区别: sybase的sql语句相应的连接有:
select * from t1,t2 where t1.c3=t2.c1 相当于内连接
select * from t1,t2 where t1.c3 *= t2.c1 相当于左外连接
select * from t1,t2 where t1.c3 =* t2.c1 相当于右外连接


总结:
内连接,全有才有;左外连接,左有就有;右外连接,右有就有;全外连接,全都有.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics