我正在尝试设置我的数据库并添加一些外键,但总是出现以下错误:
无法添加或更新子行:外键约束失败
我有 3 张 table 。
groups, categories and categorie_group
categorie_group 表是我的数据透视表。它只包含一个categorie_id和一个group_id
两者都可以为 NULL。
组和类别以 ID 作为主键
所有 3 个表都还没有任何数据。
Groups Table:
The ID references the categorie_group - group_id
- on delete cascade on update cascade
Categorie_Group
the group_id of categorie_group references the id of the groups table
on delete no action on update no action
the categorie_id of categorie_group references the id of the categories
table on delete no action on update no action
-------
第一个问题:
如果我想将 Categories Table
ID 中的外键添加到 categorie_Group
-> categorie_id
-
我得到一个
ALTER TABLE `categories` ADD FOREIGN KEY ( `id` ) REFERENCES `DB`.`categorie_group` (
`categorie_id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL meldet: Dokumentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`DB`.`#sql-c40_30a2caf`, CONSTRAINT `#sql-c40_30a2caf_ibfk_1` FOREIGN KEY (`id`) REFERENCES `categorie_group` (`categorie_id`) ON DELETE CASCADE ON UPDATE CASCADE)
第二个问题,如果我想将数据添加到组表中,我会得到相同的错误。
#1452 - Cannot add or update a child row: a foreign key constraint fails (`DB`.`group`, CONSTRAINT `group_ibfk_1` FOREIGN KEY (`id`) REFERENCES `categorie_group` (`group_id`) ON DELETE CASCADE ON UPDATE CASCADE)
最佳答案
您必须在子列“categorie_id”中实现 FK,而不是在 PK“id”上实现。必须引用 PK“id”,并且必须引用“categorie_id”。
确保列属性 propertyes。两者(primaryKey 和 FK)必须相同。或者SGBD解决不了FK:
1-“数据类型”。将Type(INT、SMALLINT)属性作为Size属性;
2-“接受空值”。
3-“未签名”。
- 请记住,MyISAM 表引擎不接受 FK 约束,只有 InnoDB 接受。
祝你好运。
关于mysql - SQL - 无法添加或更新子行 : a foreign key constraint fails - Pivot table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45104513/