27,582
社区成员




create table ta
(
id int identity(1,1),
Name varchar(20)
)
insert ta
select '张三' union all
select '李四' union all
select '王二'
create table tb
(
id int identity(1,1),
aid varchar(20)
)
go
insert tb
select '1'union all
select '1'union all
select '1'union all
select '2'union all
select '2'union all
select '3'union all
select '3'union all
select '3'union all
select '3'
select * from tb;
select * from ta;
select ta.id aid,ta.Name,tb.id bid,tb.aid baid from ta left join tb on ta.id = tb.aid;
drop table ta;
drop table tb;
针对 2 情况 a 表 和 b 表 是一对多的关系,b 中 有一个字段是a的主键,链接语句
a left join b:
select ta.id aid,ta.Name,tb.id bid,tb.aid tbaid from ta left join tb on ta.id = tb.aid;
链接结果:
1 张三 1 1
1 张三 2 1
1 张三 3 1
2 李四 4 2
2 李四 5 2
3 王二 6 3
3 王二 7 3
3 王二 8 3
3 王二 9 3
是不是 就是 在 a 左链接 b 的时候 ,针对 a中的每一条记录 r ,都会在 b中找到 所有 和 r 相匹配的所有记录插入到结果集中,而不是 仅仅 在 b 中找到一条匹配的记录,就 开始 查 a中的下一条记录。
这话的逻辑对吗?
create table #A
(
id int,
Name varchar(20)
)
insert #A
select 1,'张三' union all
select 1,'李四' union all
select 3,'王二'
create table #B
(
id int,
aid varchar(20)
)
go
insert #B
select 1,'2,3'
select * from #b a left join #a b on a.id =b.ID
select * from #a a left outer join #b b on a.id =b.ID
drop table #A
drop table #B
给您测试数据,您自己连一下。要啥样的结果自己join~