如何正确地在 mysql table 的外键中级联删除?

How to cascade on delete in a foreign key of a mysql table correctly?

我有三个带外键的表,当我 运行 这个

"DELETE FROM Tagmap WHERE excerptID = ?"

只有 Tagmap 中的映射,ExcerptTag 中什么也没有发生。我做错了什么?

CREATE TABLE IF NOT EXISTS excerpt(
  excerptID INT UNSIGNED NOT NULL AUTO_INCREMENT, 
  title VARCHAR(255) NOT NULL, 
  text VARCHAR(2500) NOT NULL,
  comments VARCHAR(2500) NOT NULL,
  PRIMARY KEY (excerptID)
) ENGINE=INNODB CHARACTER SET utf8mb4;

CREATE TABLE IF NOT EXISTS tag(
  tagID INT UNSIGNED NOT NULL AUTO_INCREMENT,
  description VARCHAR(255) NOT NULL , 
  PRIMARY KEY (tagID)
) ENGINE=INNODB CHARACTER SET utf8mb4;

CREATE TABLE IF NOT EXISTS tagmap (
  excerptID INT UNSIGNED NOT NULL, 
  tagID INT UNSIGNED NOT NULL, 
  PRIMARY KEY (excerptID, tagID),
    CONSTRAINT excerptFK FOREIGN KEY (excerptID) REFERENCES excerpt (excerptID)
    ON DELETE CASCADE 
    ON UPDATE CASCADE,
    CONSTRAINT tagFK FOREIGN KEY (tagID) REFERENCES tag (tagID)
    ON DELETE CASCADE 
    ON UPDATE CASCADE
) ENGINE=INNODB;

这不是外键的工作方式。你从parent中删除table(这里是tag,或者excerpt),然后是children记录自动掉线。如果你考虑一下,反过来就不安全了,因为可能有多个 children 引用同一个 parent.

所以,您通常会 运行 这个查询:

DELETE FROM excerpt WHERE excerptID = ?

而外键约束的on delete cascade选项会自动删除tagmap中对应excerptID.

的所有记录