多个表的共享主键

时间:2016-03-03 22:40:08

标签: mysql sql primary-key

所以我有3张桌子:

宠物小精灵:

+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| National_ID   | int(11)     | NO   | PRI | NULL    |       |
| Picture       | longblob    | YES  |     | NULL    |       |
| Name          | varchar(15) | NO   |     | NULL    |       |
| Generation_ID | int(11)     | NO   |     | NULL    |       |
| Type1         | varchar(8)  | NO   |     | NULL    |       |
| Type2         | varchar(8)  | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+

统计数据:

+-----------------+-------------+------+-----+---------+-------+
| Field           | Type        | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| National_ID     | int(11)     | NO   | PRI | NULL    |       |
| Health_Points   | int(11)     | NO   |     | NULL    |       |
| Attack          | int(11)     | NO   |     | NULL    |       |
| Defense         | int(11)     | NO   |     | NULL    |       |
| Special_Attack  | int(11)     | NO   |     | NULL    |       |
| Special_Defense | int(11)     | NO   |     | NULL    |       |
| Speed           | int(11)     | NO   |     | NULL    |       |
| Ability1        | varchar(20) | NO   |     | NULL    |       |
| Ability2        | varchar(20) | YES  |     | NULL    |       |
+-----------------+-------------+------+-----+---------+-------+

其他:

+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| National_ID  | int(11)     | NO   | PRI | NULL    |       |
| Evolves_From | varchar(15) | YES  |     | NULL    |       |
| Species      | varchar(20) | NO   |     | NULL    |       |
| Height_inch  | int(11)     | NO   |     | NULL    |       |
| Weight_lbs   | int(11)     | NO   |     | NULL    |       |
| Capture_Rate | int(11)     | NO   |     | NULL    |       |
+--------------+-------------+------+-----+---------+-------+

我的问题是Stats表中的National_ID指向Pokemon表中的National_ID,但我不能对Misc表做同样的事情。

每当我尝试在Misc中添加外键以指向Pokemon表时,我都会遇到重复错误。请帮忙!谢谢

2 个答案:

答案 0 :(得分:0)

从错误消息中,您看起来已经拥有名为'FK_National_ID'的外键约束。尝试将其更改为'FK_Pokemon_National_ID'或其他内容,它应该有效。

这是SQL Fiddle

答案 1 :(得分:0)

每个FOREIGN KEY声明表&列名列表参考表&列名列表需要唯一的名称。 (如果你没有明确地给出一个,那么DBMS会生成一个。)