我们将不得不基于表1列项目类型联接4个表。
表A包含id,itemtype,itemid
表B包含ID,全名
表c包含ID,全名
表D包含ID,全名
表A.itemid位于ID的(表B或表C或表D)中。
我想将表A与restg表连接起来以获得全名。基于TableA列的itemtype值联接另一个表
select
tblA.itemid,y.fullname from tableA as tblA
inner join (
CASE WHEN tblA.itemtype = 1 THEN
select
tblB.itemid as id,tblB.fullname as fullname
from
tableB as tblB
where
tblB.id = tblA.itemid
WHEN tblA.itemtype = 2 THEN
select
tblC.itemid as id,tblC.fullname as fullname
from
tableC as tblC
where
tblC.id = tblA.itemid
WHEN tblA.itemtype = 3 THEN
select
tblD.itemid as id ,tblD.fullname as fullname
from
tableD as tblD
where
tblD.id = tblA.itemid
END
) as bcd on bcd.id = tblA.itemid
答案 0 :(得分:1)
您可以left join
表B
,C
和D
到表A,并在{{1}中包含列itemtype
的条件}子句:
ON
请参见demo。
或使用UNION ALL:
select
A.itemid,
coalesce(B.fullname, C.fullname, D.fullname) fullname
from A
left join B on B.id = A.itemid AND A.itemtype = 1
left join C on C.id = A.itemid AND A.itemtype = 2
left join D on D.id = A.itemid AND A.itemtype = 3
请参见demo。
答案 1 :(得分:0)
如果关联表中的列不多:
SELECT
a.itemid,
COALESCE(b.fullname, c.fullname, d.fullname, ' - Missing name - '))
FROM
tblA a
LEFT JOIN tblB b ON a.itemtype = 1 AND a.itemid = a.id
LEFT JOIN tblC c ON a.itemtype = 2 AND a.itemid = b.id
LEFT JOIN tblD d ON a.itemtype = 3 AND a.itemid = c.id