gpt4 book ai didi

sql - 如果加入返回 NULL 则执行以下操作

转载 作者:行者123 更新时间:2023-12-01 01:11:35 25 4
gpt4 key购买 nike

我有3张 table

表 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 并不总是存在,有时它也为空。

最佳答案

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

关于sql - 如果加入返回 NULL 则执行以下操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com