简体   繁体   English

使用ID T-SQL多次连接到单列

[英]Multiple Join to single column using ID T-SQL

I have following issue. 我有以下问题。 I'm trying to join three tables: 我正在尝试加入三个表:

TableA: Record_id, Reference_id, Param 表A:Record_id,Reference_id,参数

TableB: Doc_id, NameB TableB:Doc_id,NameB

TableC: Doc_id, NameC TableC:Doc_id,NameC

depending on value in TableA.Param, I need to select Name from tables B or C by joining on Reference_id 根据TableA.Param中的值,我需要通过联接Reference_id从表B或C中选择名称

I've tried to use "case" constrain, but didn't worked out :) 我尝试使用“大小写”约束,但没有解决:)

select  a.Record_id, a.Reference_id
       , case when Param = 'B' then b.NameB
              when Param = 'C' then c.NameC
from TableA as a inner join
     TableB as b on a.Reference_id = b.Doc_id inner join
     TableC as c on a.Reference_id = c.Doc_id

Any ideas? 有任何想法吗?

You could left join with that condition and take the first non-null name with coalesce() 您可以在这种情况下left join ,并通过coalesce()获得第一个非空名称

select  a.Record_id, a.Reference_id,
        coalesce(b.NameB, c.NameC) as name
from TableA as a 
left join TableB as b on a.Reference_id = b.Doc_id 
                     and Param = 'B'
                     and b.STAT = 'A'
left join TableC as c on a.Reference_id = c.Doc_id 
                     and Param = 'C'
                     and c.STAT = 'A'

BTW your query was close (missed the end ). 顺便说一句,您的查询已关闭( end缺少)。 This would have worked with left join s 这本来可以用left join s

select  a.Record_id, a.Reference_id,
        case when Param = 'B' then b.NameB
             when Param = 'C' then c.NameC
        end as name
from TableA as a 
left join TableB as b on a.Reference_id = b.Doc_id and b.STAT = 'A'
left join TableC as c on a.Reference_id = c.Doc_id and c.STAT = 'A'

Try this: 尝试这个:

SELECT a.Record_id, a.Reference_id, b.NameB AS Name
FROM TableA AS a
INNER JOIN TableB AS b ON a.Reference_id = b.Doc_id 
WHERE a.Param = 'B'

UNION

SELECT a.Record_id, a.Reference_id, c.NameC AS Name
FROM TableA AS a
INNER JOIN TableC as c ON a.Reference_id = c.Doc_id 
WHERE c.Param = 'C'
SELECT  a.Record_id, a.Reference_id,V.Name
FROM TableA AS a 
inner join
(
SELECT Doc_id id, NameB Name,'B' Type from TableB
UNION ALL
SELECT Doc_id ID, NameC name,'C' Type  From TableC
) AS V On V.ID=Reference_id AND Type=Param 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM