表A
- 家长ID
- 姓名
表B
- B key
- 家长ID
- 描述
表C
- CKey
- 家长ID
- 描述
我需要为 B/A 中与父 id 匹配的每个组合数据行返回 1 行,如果其中一个子表的行数多于另一个,则应返回该描述的一行,其中包含空值。
例如,如果数据如下
表A
1 FirstParent
2 Second Parent
表B
1 1 BDesc1
2 1 BDesc2
3 2 P2BDesc1
表C
1 1 CDesc1
2 2 P2CDesc1
3 2 P2CDesc2
如果我基于FirstParent
检索,结果应该是:
1 FirstParent BDesc1 CDesc1
1 FirstParent BDesc2 NULL
如果我基于SecondParent
检索,结果应该是:
2 SecondParent P2BDesc1 P2CDesc1
2 SecondParent NULL P2CDesc2
有没有办法不需要工会就可以做到这一点?
最佳答案
declare @ParentID int
set @ParentID = 1
select a.name,
bc.descb,
bc.descc
from TableA as a
cross join (select b.descb,
c.descc
from (select *,
row_number() over(order by b.bkey) as rn
from TableB as b
where b.parentid = @parentid) as b
full outer join
(select *,
row_number() over(order by c.ckey) as rn
from TableC as c
where c.parentid = @parentid) as c
on b.rn = c.rn) as bc
where a.parentid = @parentid
在这里试试:https://data.stackexchange.com/stackoverflow/qt/112538/
编辑:使用ExternalKey查询多个ParentID的版本
建议索引:
create index IX_B_ParentID on TableB(ParentID) include (DescB)
create index IX_C_ParentID on TableC(ParentID) include (DescC)
我将创建一个表变量来保存与ExternalKey 匹配的ParentID,然后在查询中使用它而不是TableA。
declare @ExternalKey int = 1
declare @T table(ParentID int primary key, Name varchar(20))
insert into @T (ParentID, Name)
select ParentID, NAme
from TableA
where ExternalKey = @ExternalKey
select a.name,
bc.descb,
bc.descc
from @T as a
inner join (select b.descb,
c.descc,
coalesce(b.ParentID, c.ParentID) as ParentID
from (select b.ParentID,
b.DescB,
row_number() over(partition by b.ParentID order by b.bkey) as rn
from TableB as b
where b.parentid in (select ParentID from @T)) as b
full outer join
(select c.ParentID,
c.DescC,
row_number() over(partition by c.ParentID order by c.ckey) as rn
from TableC as c
where c.parentid in (select ParentID from @T)) as c
on b.rn = c.rn and
b.ParentID = c.ParentID) as bc
on a.ParentID = bc.ParentID
关于SQL - 1 个父表,2 个子表 - 为子表中的每一行返回单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7415712/