从同一个表中连接多行

时间:2011-02-25 07:34:00

标签: mysql join

我正在尝试使用这种类型的结构查询数据库

table1

ID -> int
name -> varchar

table2

ID -> int
name1 -> int
name2 -> int
name3 -> int

其中name1到3是table1 ID。 table2的每一行可以有1到3行table1与它相关联,重要的是,ID可以重复(例如:name1和name3可以是相同的)。保证字段按顺序填充(即:如果name2为NULL name3也将是。)

我正在查询这样的数据库,以便获得与3列中的ID相关联的字符串:

SELECT t2.ID, t1a.name n1, t1b.name n2, t1c.name n3   
FROM table2 t2
LEFT JOIN table1 t1a on t2.name1 = t1a.ID,
LEFT JOIN table1 t1b on t2.name2 = t1b.ID,
LEFT JOIN table1 t1c on t2.name3 = t1c.ID

我想知道是否有办法只做一次LEFT JOIN,或者你可以建议一个更好的表设计策略来实现这一点。

由于

1 个答案:

答案 0 :(得分:0)

Select T1.ID
    , Min( Case When Z.ColNum = 1 Then Z.Name End ) As n1
    , Min( Case When Z.ColNum = 2 Then Z.Name End ) As n2
    , Min( Case When Z.ColNum = 3 Then Z.Name End ) As n3
From Table1 As T1
    Left Join   (
                Select ID, 1 As ColNum, name1 As Name 
                From Table2 
                Where name1 Is Not Null
                Union All 
                Select Id, 2, name2 
                From Table2 
                Where name2 Is Not Null
                Union All 
                Select Id, 3, name3 
                From Table2 
                Where name3 Is Not Null
                ) As Z
        On Z.ID = T1.ID
Group By T1.ID