我创建其中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_ID
是NULL
,我得到的错误:
#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
只有
你是不是要把FK放在'cat_parent_id'上? –
@AaronKent这就是我的意思是... thx指出修复 – bsapaka
太棒了。你介意把我的答案标为正确吗? –