微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mysql 中的错误 - ERROR 1215 (HY000):无法添加外键约束

如何解决mysql 中的错误 - ERROR 1215 (HY000):无法添加外键约束

我想用两个外键列引用产品详细信息表的 ID 和库存来创建表

参考表产品详情:

MysqL> describe productDetail;
+--------------+--------------+------+-----+-------------------+-----------------------------+
| Field        | Type         | Null | Key | Default           | Extra                       |
+--------------+--------------+------+-----+-------------------+-----------------------------+
| ProductName  | varchar(255) | YES  |     | NULL              |                             
|
| productPrice | double       | YES  |     | NULL              |                             |
| GST          | int(25)      | YES  |     | NULL              |                             |
| stocks       | int(11)      | NO   | PRI | NULL              |                             |
| date         | timestamp    | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| ID           | int(11)      | NO   | PRI | NULL              | auto_increment              |
+--------------+--------------+------+-----+-------------------+-----------------------------+
6 rows in set (0.00 sec)

表在哪里我必须设置外键:

MysqL> describe TodayProduction;
+-----------+---------+------+-----+---------+-------+
| Field     | Type    | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| TP_ID     | int(11) | NO   | MUL | NULL    |       |
| TP_Stocks | int(11) | NO   |     | NULL    |       |
+-----------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

我已经成功地将外键添加到对productDetail ID的TP_ID引用 但我不能将外键添加到 TP_Stocks 对 productDetail 的股票列的引用

查询添加外键

alter table TodayProduction add constraint fk_Stocks foreign key (TP_Stocks) references productDetail(stocks);

错误

ERROR 1215 (HY000): Cannot add foreign key constraint

显示引擎 INNODB 状态;

Cannot find an index in the referenced table where the
referenced columns appear as the first columns,or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12,and such columns in old tables
cannot be referenced by such columns in new tables.

解决方法

您似乎有一个复合主键。您需要使用外键引用中的所有组件:

alter table TodayProduction add constraint fk_Stocks
    foreign key (productdetail_id,TP_Stocks) references productDetail (id,stocks);

也就是说,我不明白为什么你有一个复合键。通常,名为 id 的列将是完整的主键。

,

为表 productDetail 添加索引

KEY(stocks)

您需要所有列的索引。

如果你有一个组合索引,你还需要引用组合索引列。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。