我想在现有表上应用 ON 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):无法添加或更新子行:外键约束 f 病痛。
我理解此错误是因为我在 table_products 中没有 product_id,但 table_product_varients 具有这些 product_id 的变体。
我可以通过设置应用 ON DELETE 约束
SET FOREIGN_KEY_CHECKS=0
这将应用 ON DELETE 约束,但变量不会在子表中被删除,父表(table_products)中没有 product_id
如何应用 ON DELETE 约束并删除子表中没有父表的变量?
最佳答案
您必须清理表 table_product_varients
中的无效引用,然后才能添加约束
DELETE FROM table_product_varients
WHERE product_id NOT IN (SELECT product_id FROM table_products);
关于mysql - 在应用 ON DELETE 约束时如何删除子表中的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32633138/