我有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 所以,如果在表2中找不到它,那么找到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并不总是存在,有时也为空。
答案 0 :(得分: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