2017-07-14 77 views
0

我试图建立我的DATABSE,并添加一些外键,但百达得到以下errror:SQL - 不能添加或更新子行,外键约束失败 - 透视表

无法添加或更新子行:外键约束失败

我有3个表。

groups, categories and categorie_group 

categorie_group表是我的数据透视表。它只包含一个categorie_id和一个group_id

两者都可以是NULL。

基和cateogires具有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) 

seccond问题,如果我想将数据添加到组表中,我会得到相同的错误。

#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) 

回答

0
  • 您必须实现,而不是PK “ID” 的FK在孩子列 “categorie_id”。 PK“id”必须被引用,“categorie_id”必须引用。

  • 确定列属性属性。 (primaryKey和FK)必须相同。或者SGBD解决不了的FK:

1 '数据类型'。 Type(INT,SMALLINT)属性作为Size属性;
2-'接受空'。
3-'无符号'。

  • 请记住,MyISAM表引擎不接受FK约束,只是InnoDB。

祝你好运。

+0

我会试试看。但“接受空”仅适用于FK的权利?不是为了PK吗? – dwdawdawdaw

+0

我已经给每个PK和FK一个“unsigend”,并且都共享相同的数据类型。接受空值仅适用于FK。但是这并不适用于我 – dwdawdawdaw

+0

表引擎呢?请记住,MyISAM不接受FK限制,只是InnoDB所做的。 –

相关问题