我对mysql中的自然连接有些困惑。

假设:有两个表
table1具有列:id, name, address, number (id is the PK of table1)
table2具有列:id, name, number, money (id is the PK of table2)

我已经将"id"table1用作外键,引用了"id"table2

并假设"number"中的table1"people's number"并且"number"中的table2"telephone number"这两个列的含义不同,但名称相同



当我进行table1table2的自然连接时:

mysql是否仅检查table1table2的所有列,它们的名称相同,这意味着将选择一个元组(行),当且仅当"id""name""number ”必须全部相同(例如,"id""name"相同但"number"不同,将不会选择该行)?

要么

mysql是否仅检查创建的外键,这意味着将选择行,且仅当"id"相同时才行?



另一个问题是:

在自然连接table1table2之后,将只有1列称为"id"还是2列称为"table1.id""table2.id"

的确感谢!

最佳答案

您不应该为此使用自然联接,您可能需要使用左联接。
table1是父表?至少听起来应该是这样,外键引用应该来自插入到子表中的父表。父表的每个引用ID都有一个条目,而子表的引用ID可能有很多,一个或没有条目

SELECT table1.id, table1.number AS person_number, table2.number AS phone_number
FROM table1
LEFT JOIN table2 ON table1.id = table2.id

关于mysql - Mysql的自然连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22938599/

10-11 19:19
查看更多