Mysql 表与case连接

Mysql 表与case连接,mysql,Mysql,我们必须基于表1列itemtype连接4个表 表A包含id、itemtype和itemid 表B包含id和全名 表c包含id和全名 表D包含id和全名 表A.itemid位于id的(表B或表C或表D)中 我想将表A与重新生成的表连接起来以获得全名。基于TableA列itemtype值连接另一个表 select tblA.itemid,y.fullname from tableA as tblA inner join ( CASE WHEN tbl

我们必须基于表1列itemtype连接4个表

表A包含id、itemtype和itemid

表B包含id和全名

表c包含id和全名

表D包含id和全名

表A.itemid位于id的(表B或表C或表D)中

我想将表A与重新生成的表连接起来以获得全名。基于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

您可以
将表
B
C
D
左连接到表A,并在
ON
子句中包含列
itemtype
的条件:

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
请参阅。
或与所有工会:

select
  A.itemid,
  B.fullname
from A inner join B on B.id = A.itemid 
where A.itemtype = 1
union all
select
  A.itemid,
  C.fullname
from A inner join C on C.id = A.itemid 
where A.itemtype = 2
union all
select
  A.itemid,
  D.fullname
from A inner join D on D.id = A.itemid 
where A.itemtype = 3

如果关联表中的列不多,请参阅。

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

伟大的阿克森,它工作得很好。但问题是表是不必要的连接事件,尽管ItemType不相关。例如:如果itemtype=1,则表C和表D不必要地连接。因此会影响性能。谁是Aksen?连接的原因是不能在条件中连接B、C或D(至少在没有动态sql的情况下不能)。您知道这一点,因为您试图在查询中这样做。我答案中的代码就是你能做的。而且,即使可以这样做,每次检查一个条件并连接一个表或另一个表的效率也要低得多。我的代码中的连接是必需的,因此A的每一行实际上只连接到一个表的行,因为条件和A.itemtype=?实现相同连接的另一种方法是通过UNION ALL,但这将扫描表3次,然后应用UNION。