SQL中常用的联接
内联接:只包含匹配的行,也就是只返回两个数据集都有的部分对应的行
select * from table1
[inner] join table2
on table1.column = table2.column
外联接扩展了内联接,它还返回左边或右边的数据集中不匹配的数据,不匹配的数据以NULL显示
左外联接:包含左边表的全部行(不管右边的表中是否存在与它们匹配的行)以及右边表中匹配的行
右外联接:包含右边表的全部行(不管左边的表中是否存在与它们匹配的行)以及左边表中匹配的行
select * from table1
left|right [outer] join table2
on table1.column = table2.column
全外联接:包含两个表的全部行,不管在另一个表中是否存在匹配的行
例:
create table dbo.one(
onepk int,
thing1 varchar(15)
)
create table dbo.two(
twopk int,
onepk int,
thing2 varchar(15)
)
insert dbo.one(onepk, thing1)
values(1, 'old thing')
insert dbo.one(onepk, thing1)
values(2, new thing')
insert dbo.one(onepk, thing1)
values(3, red thing')
insert dbo.one(onepk, thing1)
values(4, blue thing')
insert dbo.two(twopk, onepk, thing2)
values(1,0, 'plane')
insert dbo.two(twopk, onepk, thing2)
values(2,2, 'train')
insert dbo.two(twopk, onepk, thing2)
values(3,3, 'car')
insert dbo.two(twopk, onepk, thing2)
values(4,NULL, 'cycle')
内联接:
select thing1, thing2
from dbo.one
join dbo.two
on one.onepk = two.onepk
结果:
thing1 thing2
--------------------
new thing train
red thing car
左外联接:
select thing1, thing2
from dbo.one
left outer join dbo.two
on one.onepk = two.onepk
结果:
thing1 thing2
--------------------
old thing NULL
new thing train
red thing car
blue thing NULL
全外联接:
select thing1, thing2
from dbo.one
full outer join dbo.two
on one.onepk = two.onepk
结果:
thing1 thing2
--------------------
NULL plane
new thing train
red thing car
NULL cycle
blue thing NULL
old thing NULL
在外联接中设置条件:当使用内联接时,在join子句还是where子句制定条件的效果相同,但对于外联接情况并非如此。在join子句中制定条件时,sql server将返回外联接表的所有行,然后根据指定的条件决定返回第二个表的哪些行。
select thing1, thing2
from dbo.one
left outer join dbo.two
on one.onepk = two.onepk
and one.thing1 = 'new thing'
结果:
thing1 thing2
--------------------
old thing NULL
new thing Train
red thing NULL
blue thing NULL
如果在where字句中指定条件,sql server将首先执行联接操作,然后根据where子句对联接后的行进行筛选。
select thing1, thing2
from dbo.one
left outer join dbo.two
on one.onepk = two.onepk
where one.thing1 = 'new thing'
结果:
thing1 thing2
--------------------
new thing train

浙公网安备 33010602011771号