mysql - 外键约束 hell

标签 mysql sql foreign-keys

我有一个 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/

相关文章:

SQL - 每列的条件

ruby-on-rails - 添加 :on_delete to already existing foreign_key in rails migration

mysql - 不同的值不在查询中

php - 帮助 MySql 触发器或替代

mysql - 检测两个 MySQL 列中的重复项(分散在列中的唯一值)

sql - 如何在 SQL Server 中连接字符串消息和列值

python - 如何访问链接的父模型的数据库模型字段,例如类(class)->学校->用户?

python - Mysql 创建外键

php - 访问我的 MySQL 数据库被拒绝

php - mysql 选择 2 个表并按日期对其中 1 个进行排序(更接近当前时间)