在sqlserver中对多个表的左外部联接

问题描述 投票:0回答:1

我的目标是拥有2个主表和多个具有某些附加值的附加表。当只有一个主表时,它可以与左外部联接一起使用。一旦添加第二个主表,sql就会出现语法错误。

CREATE TABLE A(
 avalue [char](1),
 id_a int IDENTITY(1,1) not null PRIMARY KEY
)

CREATE TABLE B(
 bvalue [char](1),
 id_b int IDENTITY(1,1) not null PRIMARY KEY
)

CREATE TABLE C(
 cvalue [char](1),
 id_a int FOREIGN KEY REFERENCES a(id_a),
 id_b int FOREIGN KEY REFERENCES b(id_b),
 id_c int IDENTITY(1,1) not null PRIMARY KEY
)

CREATE TABLE D(
 dvalue [char](1),
 id_a int FOREIGN KEY REFERENCES a(id_a),
 id_b int FOREIGN KEY REFERENCES b(id_b),
 id_d int IDENTITY(1,1) not null PRIMARY KEY
)


insert into a (avalue) values ('A');
insert into a (avalue) values ('X');
insert into b (bvalue) values ('B');
insert into c (cvalue,id_a,id_b) values ('C',1,1);
insert into d (dvalue,id_a,id_b) values ('D',1,1);


select a.avalue, c.cvalue
from a
left outer join c on a.id_a = c.id_a
where a.id_a=1

A C


-- not working
-- Msg 4104, Level 16, State 1, Line 3
-- The multi-part identifier "a.id_a" could not be bound.

select a.avalue, b.bvalue, c.cvalue, d.dvalue
from a,b
left outer join c on a.id_a = c.id_a
left outer join d on a.id_a = d.id_a
where a.id_a=1
and b.id_b=1

-- expected
A B C D

X Y null null

我的目标是让sql语句始终返回主值和所有扩展值,即使它们不存在。

sql-server left-join outer-join
1个回答
0
投票

关于以下内容...如上所述,我假设'Y'是一个拼写错误,您要么打算键入'B',要么您忘记插入'Y'

select a.avalue, b.bvalue, c.cvalue, d.dvalue
from a
outer apply( select * from b ) b
left outer join c on a.id_a = c.id_a
left outer join d on a.id_a = d.id_a
© www.soinside.com 2019 - 2024. All rights reserved.