多表连接

多表连接

按连接条件:等值和非等值。
按连接方法:外部和内部。
select table1.column,table2.column
from table1,table2
where teble.column=table2.column

笛卡尔积

一边a人,另一边有b人,则a和b组合有a*b种。
上述就相当于做了一个笛卡尔积。

外连接

select table1.column,table2.column
from table1,table2
where teble.column(+)=table2.column
哪边有+哪边就可以有空行(从表),另外一边多(主表),只能在一边使用。

自身连接(自连接)

select x1.a,x2.b
from x x1,x x2
where x1.c1=x2.c2
(x1、x2为别名,c1和c2为内容相同的行)

cross join

select a,b
from x
cross join y
产生笛卡尔积

natural join自然连接

select a,b
from x
natural join y
相当于等值连接

using

select a,b
from x join y using(c)
指定c连接x、y两张表,也是等值连接。
与natural join不能同时使用。

on

select a,b
from x join y on x.c=y.c
指定连接条件。

左外连接

select a,b
from x left join y on x.c=y.c
左边主表,右边从表。

右外连接

select a,b
from x right join y on x.c=y.c
右边主表,左边从表。
自身链接(自连接)也可以使用左(右)连接。
注意搞清楚左(右)外连接和外连接写法,主表没空格,副标有空格。

全外连接

select a,b
from x full outer join y on x.c=y.c
全都显示,不分主表从表,左右都可以空。