我想对现有表上的DELETE约束应用。为此,我使用以下查询:
mysql> alter table table_product_varients add constraint fk_test foreign key (product_id) references table_products (product_id) on delete cascade ;并得到这个错误:
错误1452 (23000):无法添加或更新子行:外键约束child。
我理解这个错误是因为我没有product_id在table_products中,但是table_product_varients有那些product_ids的变量。
我可以通过设置
SET FOREIGN_KEY_CHECKS=0 这将适用于DELETE约束,但是变量不会在子表中被删除,因为它们在父表中没有product_id (Table_products)。
如何在DELETE约束上应用,同时也删除子表中的变量,以便它们没有可用的父级?
发布于 2015-09-17 14:51:14
必须清除表table_product_varients中的无效引用,然后才能添加约束。
DELETE FROM table_product_varients
WHERE product_id NOT IN (SELECT product_id FROM table_products);发布于 2015-09-17 14:42:59
//这将删除没有父母的孩子
DELETE FROM TABLE_PRODUCTS
WHERE PRODUCT_VARIENT_ID NOT IN (SELECT ID FROM TABLE_PRODUCT_VARIENTS);//之后,您可以应用您的外键
https://stackoverflow.com/questions/32633138
复制相似问题