mysql自然连接不起作用

时间:2015-01-17 21:57:25

标签: mysql inner-join natural-join

我在mysql服务器中有两个表。我使用这些表来研究JOIN多个表,但似乎有些不正确:

mysql> select * from category;
+-------------+-----------+
| category_id | name      |
+-------------+-----------+
|           1 | fruit     |
|           2 | vegetable |
+-------------+-----------+
2 rows in set (0.00 sec)

mysql> desc category;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| category_id | int(11)     | NO   | PRI | NULL    | auto_increment |
| name        | varchar(50) | NO   |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> select * from goods;
+---------+--------+-------------+------+
| good_id | name   | category_id | cost |
+---------+--------+-------------+------+
|       1 | banan  |           1 | 1.00 |
|       2 | potato |           2 | 1.00 |
|       3 | peach  |           1 | 1.00 |
+---------+--------+-------------+------+
3 rows in set (0.00 sec)

mysql> desc goods;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| good_id     | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(100) | NO   |     | NULL    |                |
| category_id | int(11)      | NO   | MUL | NULL    |                |
| cost        | decimal(6,2) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

第二个表有外键(category_id),我可以使用INNER JOIN加入它们:

mysql> select c.name category, g.name, g.cost from category as c INNER JOIN goods g ON c.category_id = g.category_id;
+-----------+--------+------+
| category  | name   | cost |
+-----------+--------+------+
| fruit     | banan  | 1.00 |
| vegetable | potato | 1.00 |
| fruit     | peach  | 1.00 |
+-----------+--------+------+
3 rows in set (0.00 sec)

我尝试使用NATURAL JOIN,但它没有用,似乎我不知道为什么((

mysql> select c.name, g.name, g.cost from category as c NATURAL JOIN goods g;
Empty set (0.00 sec)

有人可以解释为什么NA​​TURAL JOIN不起作用吗?

1 个答案:

答案 0 :(得分:4)

我遇到了完全相同的事情,我的谷歌搜索让我想到了这个问题。我最终弄明白了,所以我想我会在这里发布我的答案。

这是罪魁祸首:

  

不是通过ON,USING或WHERE子句指定连接条件,而是NATURAL关键字告诉服务器匹配两个表之间的任何列名,并自动使用这些列来解析连接。

您的水果和类别表都有一个名为" name"的列。当SQL尝试加入这两者时,它会尝试加入 all like columns 。因此,category_id == category_id,但名称!=名称。

重命名列 tablename _column。