0

I'm a little confused about the natural join in mysql.

Suppose that: There are two tables
table1 has columns: id, name, address, number (id is the PK of table1)
table2 has columns: id, name, number, money (id is the PK of table2)

I have already make "id" of table1 a foreign key, referencing the "id" of table2

and suppose "number" in table1 is "people's number" and "number" in table2 is "telephone number" those two columns have different meaning but same name


When I do the natural join of table1 and table2:

Does mysql just simply check all the columns of table1 and table2, whose name are same, which means that a tuple(row) will be selected ,if and only if, "id", "name" and "number" must be all same (for example, the "id" and "name" are same but "number" is different, the row will not be selected)?

OR

Does mysql will only check the foreign keys created, which means that a row will be selected , if and only if, "id" is same?


another question is:

after natural join of table1 and table2, will there be only 1 column called "id" or 2 columns called "table1.id" and "table2.id"??

Thanks indeed!

4

2 回答 2

0

您不应该为此使用自然连接,您可能需要使用左连接。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
于 2014-04-08T13:45:04.210 回答
0

无论外键如何,仅读取数据的查询将始终给出相同的结果。

JOIN 手册

两个表的 NATURAL [LEFT] JOIN 被定义为在语义上等同于 INNER JOIN 或 LEFT JOIN,并带有一个命名两个表中存在的所有列的 USING 子句。

如果您SELECT *在 NATURAL JOIN 中使用的列将仅在结果集中出现一次。

所以,在你的情况下:

SELECT * FROM table1 NATURAL JOIN table2

会变成:

SELECT table1.id, table1.name, table1.number, table1.address, table2.money
FROM table1 
JOIN table2 ON table2.id = table1.id 
           AND table2.name = table1.name 
           AND table2.number = table1.number

列的顺序很可能

于 2014-04-08T13:47:23.780 回答