在父表中:
Id int identity(1,1) not null primary key,
Firstname varchar(50),
Email varchar(50)
在子表中:
Mid int identity(1,1) not null primary key,
Mark1 int,
Mark2 int,
Id int not null foreign key references Parent(Id)
在标记表中:
Uid int identity(1,1) not null primary key,
Mark3 int,
Id int not null foreign key references Parent(Id)
select Id,Firstname,Null as Mark1,Null as Mark2,Null as Mark3 from Parent
union
select Id,Null as Firstname,Mark1,Mark2,Null as Mark3 from Child
union
select Null as Id,Null as Firstname,Null as Mark1,Null as Mark2,Mark3 from Mark
select * from (select Parent.Id,Parent.Firstname,Null as Mark1,Null as Mark2 from Parent
union all
select Id,Null as Firstname, Mark1,Mark2 from Child) t1 inner join Mark t2 on t2.Id=t1.Id
但是无法得到它。
所以我希望最终结果应该基于用户何时给出Id。
例如:
Id Firstname Mark1 Mark2 Mark3
-- --------- ----- ----- -----
2 john 89 70 60
答案 0 :(得分:0)
根据评论更新 是否可以在不使用连接查询的情况下合并三个表,这意味着我们可以使用联合查询吗?
select
Id,
MAX(Firstname) Firstname,
MAX(Mark1) Mark1,
MAX(Mark2) Mark2,
MAX(Mark3) Mark3
from
(
select Id,Firstname,Null as Mark1,Null as Mark2,Null as Mark3 from Parent
union
select Id,Null as Firstname,Mark1,Mark2,Null as Mark3 from Child
union
select Id,Null as Firstname,Null as Mark1,Null as Mark2,Mark3 from Mark
) t
group by id
也许你需要加入
select
p.*, c.Mark1,c.Mark2,m.Mark3
from parent p
left join child c
on p.id=c.id
left join marks m
on m.id=p.id
--where p.id=@userprovidedId
请注意,当Child或Marks表中有多个行用于相同的parentid时,这将提供多行
答案 1 :(得分:0)
select
p.*, Mark1,Mark2,m.Mark3
from parent p
join child c
on p.id=c.id
join marks m
on m.id=p.id