gpt4 book ai didi

MySQL LEFT JOIN 一致地从多个表返回数据

转载 作者:行者123 更新时间:2023-11-29 21:43:14 24 4
gpt4 key购买 nike

首先,对这个问题的措辞表示歉意,因为它对我来说似乎相当不够。

我有三个表:t1t2t3。它们都共享一个外键id,这也是它们的主键。我想做这样的事情:

SELECT col1, col2 FROM t1 LEFT JOIN (t2, t3) ON (t1.id=t2.id AND t1.id=t3.id);

当然,当 t1 没有匹配行时,查询将返回空,即使其他表有匹配行。我无法预测哪个表可能包含或不包含数据,但我仍然想返回值(对于不匹配的表使用 NULL )。我该怎么做?

我猜根据 LEFT JOIN 的定义,这是预期的行为。所以,也许我应该使用另一种 JOIN!

编辑

t1

id col1 col2
------------------

<EMPTY>


t2
-----
id col3 col4
------------------
1 foo bar
2 faa boo
3 faz baz



t3
-----
id col5 col6
------------------
3 hoo har
4 haa boo

当我这样做时:

    SELECT * FROM t1 <WHATEVER JOIN> (t2, t3) ON (t1.id=t2.id AND t1.id=t3.id) WHERE id = 3;

我想看到类似的内容:

id: NULL
col1: NULL
col2: NULL
col3: faz
col4: baz
col5: hoo
col6: har

最佳答案

对于您提供的具体示例,此查询将为您提供正确的结果:

SELECT t1.id as id,
t1.col1 as col1,
t1.col2 as col2,
b.col3 as col3,
b.col4 as col4,
b.col5 as col5,
b.col6 as col6
FROM t1
RIGHT JOIN (
SELECT t2.id as id,
t2.col3 as col3,
t2.col4 as col4,
t3.col5 as col5,
t3.col6 as col6
FROM t2
JOIN t3 ON t2.id = t3.id) B
on t1.id = b.id;

关于MySQL LEFT JOIN 一致地从多个表返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34316569/

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