外键约束:何时使用 ON UPDATE 和 ON DELETE

2022-01-20 00:00:00 sql database foreign-keys mysql

我正在使用 MySQL Workbench 设计我的数据库架构,这非常酷,因为您可以制作图表并转换它们:P

I'm designing my database schema using MySQL Workbench, which is pretty cool because you can do diagrams and it converts them :P

无论如何,我决定使用 InnoDB 是因为它支持外键.我注意到的一件事是,它允许您为外键设置 On Update 和 On Delete 选项.谁能解释一下Restrict"、Cascade"和 set null 可以在一个简单的例子中使用吗?

Anyways, I've decided to use InnoDB because of it's Foreign Key support. One thing I noticed though is that it allows you to set On Update and on Delete options for foreign keys. Can someone explain where "Restrict", "Cascade" and set null could be used in a simple example?

例如,假设我有一个包含 userIDuser 表.假设我有一个消息表 message 是多对多的,它有 2 个外键(在 user 中引用相同的主键 userID 表).在这种情况下,设置 On Update 和 On Delete 选项有用吗?如果是这样,我该选择哪一个?如果这不是一个很好的例子,你能想出一个很好的例子来说明这些如何有用吗?

For example, say I have a user table which includes a userID. And say I have a message table message which is a many-to-many which has 2 foreign keys (which reference the same primary key, userID in the user table). Is setting the On Update and On Delete options any useful in this case? If so, which one do I choose? If this isn't a good example, could you please come up with a good example to illustrate how these could be useful?

谢谢

推荐答案

不要犹豫,对数据库进行约束.您一定会拥有一个一致的数据库,这是使用数据库的充分理由之一.特别是如果您有多个应用程序请求它(或只有一个应用程序,但具有直接模式和使用不同来源的批处理模式).

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

使用 MySQL,您不会像在 postgreSQL 中那样拥有高级约束,但至少外键约束非常高级.

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

我们举个例子,一个公司表和一个用户表,其中包含来自这些公司的人

We'll take an example, a company table with a user table containing people from theses company

CREATE TABLE COMPANY (
     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)
) ENGINE=INNODB;

CREATE TABLE USER (
     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;

让我们看看ON UPDATE子句:

  • ON UPDATE RESTRICT:默认值:如果您尝试更新表 COMPANY 中的 company_id,如果一个用户至少链接到该公司,引擎将拒绝该操作.
  • ON UPDATE NO ACTION:与 RESTRICT 相同.
  • ON UPDATE CASCADE:通常是最好的:如果您在 COMPANY 表的一行中更新 company_id,引擎将在引用该 COMPANY 的所有 USER 行上相应地更新它(但没有在 USER 表上激活触发器,警告).引擎会为您跟踪更改,这很好.
  • ON UPDATE SET NULL :如果您在 COMPANY 表的一行中更新 company_id,引擎会将相关的 USERs company_id 设置为 NULL(应该在 USER company_id 字段中可用).我在更新中看不到任何有趣的事情,但我可能错了.
  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE NO ACTION : same as RESTRICT.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

现在在 ON DELETE 方面:

  • ON DELETE RESTRICT:默认值:如果您尝试删除表 COMPANY 中的 company_id Id,如果一个用户至少链接到该公司,引擎将拒绝该操作,可以挽救你的生命.
  • ON DELETE NO ACTION:与 RESTRICT 相同
  • ON DELETE CASCADE:危险:如果您删除表 COMPANY 中的公司行,引擎也会删除相关的 USER.这很危险,但可用于对辅助表进行自动清理(因此可以是您想要的,但对于 COMPANY<->USER 示例肯定不是)
  • ON DELETE SET NULL:handful:如果您删除 COMPANY 行,相关的 USER 将自动与 NULL 建立关系.如果 Null 是您对没有公司的用户的价值,这可能是一种很好的行为,例如,您可能需要将用户保留在您的应用程序中,作为某些内容的作者,但删除公司对您来说不是问题.
  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE NO ACTION : same as RESTRICT
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

通常我的默认设置是:ON DELETE RESTRICT ON UPDATE CASCADE.带有一些 ON DELETE CASCADE 用于跟踪表(日志——不是所有日志——,类似的东西)和 ON DELETE SET NULL 当主表是一个简单属性"时' 用于包含外键的表,就像 USER 表的 JOB 表.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.

编辑

很久没写了.现在我想我应该添加一个重要的警告.MySQL 对级联有一个很大的记录限制.级联不会触发触发器.因此,如果您对该引擎有足够的信心使用触发器,则应避免级联约束.

It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

  • http://dev.mysql.com/doc/refman/5.6/en/triggers.html

MySQL 触发器仅针对 SQL 语句对表所做的更改激活.它们不会因视图的更改而激活,也不会因不将 SQL 语句传输到 MySQL 服务器的 API 对表的更改而激活

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

  • http://dev.mysql.com/doc/refman/5.6/en/stored-program-restrictions.html#stored-routines-trigger-restrictions
  • ==> 见下方最后的编辑,这个域正在发生变化

    外键操作不会激活触发器.

    Triggers are not activated by foreign key actions.

    而且我认为这不会有一天会得到解决.外键约束由 InnoDb 存储管理,触发器由 MySQL SQL 引擎管理.两者是分开的.Innodb 是唯一有约束管理的存储,也许有一天他们会直接在存储引擎中添加触发器,也许不会.

    And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

    但是我有我自己的观点,你应该在糟糕的触发器实现和非常有用的外键约束支持之间选择哪个元素.一旦你习惯了数据库的一致性,你就会爱上 PostgreSQL.

    But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

    正如@IstiaqueAhmed 在评论中所说,这个问题的情况已经发生了变化.因此,请点击链接并查看真实的最新情况(将来可能会再次更改).

    as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

相关文章