gpt4 book ai didi

mysql - 仅当字段不为空时才进行内部连接

转载 作者:IT老高 更新时间:2023-10-29 00:20:18 26 4
gpt4 key购买 nike

我可以用两个请求完成我想要的,但我只想用一个来完成。

事实上,我有 4 个表:

Table 1 : id, sub-id
Table 2 : id, sub-id
Table 3 : id, login
Table 4 : id, login

我提出这样的要求:

SELECT Table1.id, Table1.sub-id, Table2.id, Table2.sub-id, 
Table3.login, Table4.login FROM Table1
INNER JOIN Table2 ON (Table1.id = Table2.id AND Table1.sub-id = Table2.sub-id)
INNER JOIN Table3 ON (Table3.id = Table1.id)
INNER JOIN Table4 ON (Table4.id = Table1.id)
WHERE Table1.id = "my_id" AND Table1.sub-id = "my_subid"

我想加入Table3,只有id不为空,如果为空,我加入Table4

请问您有什么想法吗?

我听说左连接会有所帮助,但我不太习惯这些关键字,所以...?

最佳答案

就像其他答案中所说的,您可以使用左连接。您还可以添加 case statement只有一个 login 列:

SELECT 
Table1.id,
Table1.sub-id,
Table2.id,
Table2.sub-id,
CASE
WHEN Table3.id IS NOT NULL THEN Table3.login
ELSE Table4.login
END CASE AS login
FROM Table1
INNER JOIN Table2 ON (Table1.id = Table2.id AND Table1.sub-id = Table2.sub-id)
LEFT JOIN Table3 ON (Table3.id = Table1.id)
LEFT JOIN Table4 ON (Table4.id = Table1.id)
WHERE Table1.id = "my_id" AND Table1.sub-id = "my_subid"

关于mysql - 仅当字段不为空时才进行内部连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5979508/

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