我在子表上应用了DELETE CASCADE和UPDATE CASCADE约束。
alter table table_product_categories add constraint fk_product_id1 foreign key (product_id) references table_products (product_id) on delete cascade;
alter table table_product_categories add constraint fk_product_id2 foreign key (product_id) references table_products (product_id) on update cascade;
现在尝试在父表中删除时:
DELETE FROM table_products WHERE `table_products`.`product_id` = 1819
出现此错误:
MySQL说:文档
1451 - 无法删除或更新父行:外键约束失败(`table_product_categories`,CONSTRAINT`fk_product_id1` FOREIGN KEY(`product_id`)REFERENCES`table_products`(`product_id`)ON UPDATE CASCADE)
尝试更新父表时
UPDATE `wokoshop`.`table_products` SET `product_id` = '1' WHERE `table_products`.`product_id` =1819
出现此错误:
1452 - 无法添加或更新子行:外键约束失败(`wokoshop` .table_product_categories`,CONSTRAINT`fk_product_id2` FOREIGN KEY(`product_id`)REFERENCES`table_products`(`product_id`)ON DELETE CASCADE )
错误的原因是什么以及如何解决?
答案 0 :(得分:1)
不要创建两个约束,而是使用两个CASCADE
选项的单个约束:
alter table table_product_categories
add constraint fk_product_id1 foreign key (product_id)
references table_products (product_id)
on delete cascade on update cascade;