gpt4 book ai didi

mysql - 尽管加入,但列出所有行

转载 作者:行者123 更新时间:2023-11-29 04:07:52 25 4
gpt4 key购买 nike

我不明白为什么我尝试的方法不起作用。

我有两张 table

Table1
id_tb1 | tb1field
1 aaa
2 bbb
3 ccc
4 ddd
5 eee

Table2
id_stuff | id_tb1
1 1
1 4
1 5
2 1
3 1

id 需要的是加入 tb1 和 tb2,同时列出 tb1 中的所有记录。像这样:

Result
id_tb1 | tb1field | tb2.id_stuff
1 aaa 1
2 bbb NULL
3 ccc NULL
4 ddd 1
5 eee 1

所以我这样做了:

SELECT t1.*, t2.id_stuff
FROM Table1 t1
LEFT JOIN Table2 t2 ON t2.id_tb1 = t1.id_tb1
WHERE t2.id_stuff = 1

但显然,这不是好的解决方案。有人有一个想法吗?谢谢。

最佳答案

如果您在 WHERE 子句中对 LEFT JOINed 表添加条件,这就像您在何处执行 INNER JOIN 一样。

将该条件添加到左连接

SELECT t1.*, t2.id_stuff
FROM Table1 t1
LEFT JOIN Table2 t2 ON t2.id_tb1 = t1.id_tb1 and t2.id_stuff = 1

关于mysql - 尽管加入,但列出所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427170/

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