我正在尝试解析 MySQL docs .他们可以更清楚。他们似乎在说有五种可能性:SET NULL、NO ACTION、RESTRICT、CASCADE 和 SET DEFAULT。
NO ACTION 和 RESTRICT 做同样的事情(防止任何破坏 FK 的 DB 更改)并且该事情是默认设置,因此如果您省略 ON DELETE 子句,您就是在说 NO ACTION(或 RESTRICT——同样的事情)。
SET NULL 允许删除父行,将 FK 设置为 NULL。
CASCADE 删除子行。
SET DEFAULT 永远不应该被使用。
这或多或少是正确的吗?
最佳答案
是的,没错:
NO ACTION: [...] InnoDB rejects the delete or update operation for the parent table.
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. [...]
显然 NO ACTION
和 RESTRICT
是同义词。此外,由于在没有 ON DELETE/UPDATE
子句时使用它们,因此这是默认行为。
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. [...]
外部列设置为 NULL,前提是它未声明为 NOT NULL(或 InnoDB 不允许删除或更新)。
CASCADE: Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. [...]
级联删除(或更新)外部列。
SET DEFAULT: This action is recognized by the parser, but InnoDB rejects table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.
所以基本上你不能使用那个选项。
https://stackoverflow.com/questions/1027656/