我有一个 MySQL InnoDB 数据库,其中包含用户、产品、品牌和类别。
涉及很多外键 - 用户添加的产品、产品品牌、产品类别、关注品牌的用户...
每次我尝试删除一条记录时,一个外键约束失败,然后我去删除另一条记录,另一条记录又因为其他原因失败,它们都纠结在一起。
这就是我设置它们的方式:
ON DELETE restrict
ON UPDATE cascade
我不知道为什么,我只是读到这样设置很好。
我希望能够完美地删除记录,我该怎么做?与此不同的另一种方法的最终缺点是什么?
最佳答案
正如您所使用的那样 -
ON DELETE RESTRICT
当其他记录存在时,DBMS 不会让您删除任何相关记录。要在删除父记录时删除所有子表中的所有相关记录,请使用
ON DELETE CASCADE
或
ON DELETE SET NULL
如果您希望外键字段设置为NULL
来自doc -
- CASCADE: Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. Between two tables, do not define several ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table. Note: Currently, cascaded foreign key actions do not activate triggers.
- RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.
- SET NULL: Delete or update the row from the parent table, and set the foreign key column or columns in the child table to NULL. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.
关于mysql - 外键约束 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20918703/