2015-04-23 117 views
0

我创建其中cat_parent_id是一个外键的主键cat_id限制的表,使用此约束:MySQL的 - 外键在同一个表的主键,错误#1452

CREATE TABLE categories (
    cat_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    cat_parent_ID SMALLINT, 
    cat_name VARCHAR(40) 

    INDEX cat_id(cat_id), 
    FOREIGN KEY(cat_id) REFERENCES categories(cat_id),  
); 

当我尝试插入一条记录,其中cat_parent_IDNULL,我得到的错误:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`categories`, CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`cat_id`) REFERENCES `categories` (`cat_id`)) 

如何能在没有外键开始与外键约束失败?只有在不允许null的情况下,约束才有可能?

我只能成功插入记录,如果我禁用约束,这不是我想要的。我需要parent_id是可选的,如果它有一个值,那么它是现有的cat_id只有

+1

你是不是要把FK放在'cat_parent_id'上? –

+0

@AaronKent这就是我的意思是... thx指出修复 – bsapaka

+0

太棒了。你介意把我的答案标为正确吗? –

回答

0

这将创建一个循环外键,这将防止任何插入到表中。

FOREIGN KEY(cat_id) REFERENCES categories(cat_id), 

编辑:也许你打算把cat_parent_id上的PK?

0

您有一个没有父级的根记录。对于这个,你必须先禁用外键约束。

SET FOREIGN_KEY_CHECKS=0; 

插入记录。

然后不要忘记从现在开始重新enble外键约束

SET FOREIGN_KEY_CHECKS=1; 

然后自己,请确保您的刀片包括现有的父。

How can the foreign key constraint fail when there is no foreign key to begin with? Is the constraint only possible if null is not allowed?

如果要添加其他没有FK值的记录,请确保允许NULL。