gpt4 book ai didi

mysql - 带有两个外键的自然 JOIN

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

我有那两个表

id | name |
___________
1 | John |
2 | Mike |

id | id_name1 | id_name2
________________________
1 | 2 | 1
2 | 1 | null

第一个表的主键是第二个表中的 ID 我有两个外键 ID_NAME1 和 ID_NAME2,它们引用第一个表中的主键。使用后

SELECT table1.name, table2.id FROM table1 NATURAL JOIN table 2

我明白了

John 1
John 2
Mike 1
Mike 2

但是我想要

John 1
John 2
Mike 2

我做错了什么?

最佳答案

你不需要 natural join 我猜你期望的是:

http://sqlfiddle.com/#!9/c9b1d/7

SELECT table1.name, table2.id
FROM table1
LEFT JOIN table2
ON table1.id = table2.id_name1
OR table1.id = table2.id_name2
ORDER BY table1.id,table2.id

关于mysql - 带有两个外键的自然 JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29732481/

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