4

我有 3 张桌子

表格1

ID NAMEID OTHER
--------------------------------------
1  12345  BLAH
2  23456  BLAH
3  25896  BLAH
4  74896  BLAH
5  95124  BLAH
6  63258  BLAH
7  99999  BLAH

表2

TID    Name
-------------------------------------
12345  Apple
23456  Orange
25896  Banana
74896  Grape
95124  Lime
63258  Berry

表3

ID    Start_Date  End_Date Alt_Name
-------------------------------------
9999     BLAH       BLAH       Pears
12345    BLAH       BLAH             
23456    BLAH       BLAH       Orange

关系

 Table1.NAMEID = Table2.TID
 Table1.ID     = Table3.ID

有时在 Table2.TID 中找不到 NameID,因此如果在 table2 中找不到,则查找 table3。

这是查询和当前结果

Select 
      Table1.ID
      Table2.Name
      Table3.Start_Date
      Table3.End_Date
      Table1.Other
from Table1 Table1
left outer join Table3 Table3 ON Table1.ID     = Table3.ID
left outer join Table2 Table2 On Table1.NAMEID = Table2.TID

电流 - 输出

ID    Name    Start_Date  End_Date    Other
-------------------------------------------
1     Apple      Blah       Blah       Blah
2     Orange     Blah       Blah       Blah
3     Banana     Blah       Blah       Blah
4     Grape      Blah       Blah       Blah
5     Lime       Blah       Blah       Blah
6     Berry      Blah       Blah       Blah
7      NULL      Blah       Blah       Blah 

我想要的输出

ID    Name    Start_Date  End_Date    Other
-------------------------------------------
1     Apple      Blah       Blah       Blah
2     Orange     Blah       Blah       Blah
3     Banana     Blah       Blah       Blah
4     Grape      Blah       Blah       Blah
5     Lime       Blah       Blah       Blah
6     Berry      Blah       Blah       Blah
7     Pears      Blah       Blah       Blah      

在表 3 中,对于每个 ID,Alt_Name 并不总是存在,有时它也为空。

4

1 回答 1

4
SELECT  a.ID,
        COALESCE(b.Name, c.AltName, '-no name-') as `Name`
        c.Start_DATE,
        c.End_DATE,
        a.Other
FROM    table1 a
        LEFT JOIN table2 b
            ON a.nameID = b.tid
        LEFT JOIN table3 c
            ON a.NameID = c.ID
于 2013-02-27T14:59:19.157 回答