我对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"
这两个列的含义不同,但名称相同
当我进行table1
和table2
的自然连接时:
mysql是否仅检查table1
和table2
的所有列,它们的名称相同,这意味着将选择一个元组(行),当且仅当"id"
,"name"
和"number
”必须全部相同(例如,"id"
和"name"
相同但"number"
不同,将不会选择该行)?
要么
mysql是否仅检查创建的外键,这意味着将选择行,且仅当"id"
相同时才行?
另一个问题是:
在自然连接table1
和table2
之后,将只有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/