连接也称为θ连接。它是从两个关系的笛卡尔积中选取属性间满足一定条件的元组。
连接运算中有两种最为重要的连接,一种是等值连接(Equijoin),另一种是自然连接(Nature Join):等值连接是从关系R和S中的笛卡尔积中选取A,B属性值相等的那些元组;自然连接它要求两个关系中进行比较的分量必须是相同的属性组,并且把结果中重复的属性列去掉。
Example:
create table R ( A varchar2(10), B varchar2(10), C varchar2(10) ); insert into R(A,B,C) values ('a1','b1','5'); insert into R(A,B,C) values ('a1','b2','6'); insert into R(A,B,C) values ('a2','b3','8'); insert into R(A,B,C) values ('a2','b4','12'); create table S( B varchar2(10), D varchar2(10) ); insert into S(B,D) values ('b1','3'); insert into S(B,D) values ('b2','7'); insert into S(B,D) values ('b3','10'); insert into S(B,D) values ('b3','2'); insert into S(B,D) values ('b5','2'); commit;
R |
|||
A |
B |
C |
|
a1 |
b1 |
5 |
|
a1 |
b2 |
6 |
|
a2 |
b3 |
8 |
|
a2 |
b4 |
12 |
|
S |
|||
B |
D |
||
b1 |
3 |
||
b2 |
7 |
||
b3 |
10 |
||
b3 |
2 |
||
b5 |
2 |
关系R和关系S分别如上图所示。
1、一般连接(C<D)
R-S(C<E) |
||||
A |
R.B |
C |
S.B |
D |
a1 |
b1 |
5 |
b1 |
3 |
a1 |
b1 |
5 |
b2 |
10 |
a1 |
b2 |
6 |
b2 |
7 |
a1 |
b2 |
6 |
b3 |
10 |
a2 |
b3 |
8 |
b3 |
10 |
2、等值连接(select * from (select * from R) R join (select * from S) S on R.B=S.B)
A |
R.B |
C |
S.B |
D |
a1 |
b1 |
5 |
b1 |
3 |
a1 |
b2 |
6 |
b2 |
7 |
a2 |
b3 |
8 |
b3 |
10 |
a2 |
b3 |
8 |
b3 |
2 |
3、自然连接(select A,S.B(R.B)as B,C,D from (select * from R) R join (select * from S) S on R.B=S.B)
A |
B |
C |
D |
a1 |
b1 |
5 |
3 |
a1 |
b2 |
6 |
7 |
a2 |
b3 |
8 |
10 |
a2 |
b3 |
8 |
2 |
4、外连接(Outer JOIN)
A |
B |
C |
D |
a1 |
b1 |
5 |
3 |
a1 |
b2 |
6 |
7 |
a2 |
b3 |
8 |
10 |
a2 |
b3 |
8 |
2 |
a2 |
b4 |
12 |
NULL |
NULL |
b5 |
NULL |
2 |
4.1 左外连接(Left Join:select A,S.B(R.B) as B,C,D from (select * from R) R Left join (select * from S) S on R.B=S.B)
只保留左边关系R中要舍弃的元组。
A |
B |
C |
D |
a1 |
b1 |
5 |
3 |
a1 |
b2 |
6 |
7 |
a2 |
b3 |
8 |
10 |
a2 |
b3 |
8 |
2 |
a2 |
b4 |
12 |
NULL |
4.2 右外连接(Right Join:select A,S.B(R.B) as B,C,D from (select * from R) R right join (select * from S) S on R.B=S.B)
只保留右边关系S中要舍弃的元组。
A |
B |
C |
D |
a1 |
b1 |
5 |
3 |
a1 |
b2 |
6 |
7 |
a2 |
b3 |
8 |
10 |
a2 |
b3 |
8 |
2 |
NULL |
b5 |
NULL |
2 |