[英]Can't create a Many-To-One relation with all-delete-orphan cascade. MySQL says a foreign key constraint fails when deleting the parent
[英]Mysql 'Cascade On Delete' Not Deleting on Foreign Key Row When Parent Is Deleted
在数据库中,我有一个用户名表和管辖区表。 我还有一个中间表,用于将用户分配到一个或多个司法管辖区。
employee table
userID (primary Key)
firstName
lastName
records:
+--------+-----------+----------+
| userID | firstName | lastName |
+--------+-----------+----------+
| 6 | John | Doe |
| 11 | lisa | lopez |
+--------+-----------+----------+
jurisdictions table
jurId (Primary Key)
region
records:
+-------+--------------+
| jurID | jurisdiction |
+-------+--------------+
| 1 | California |
| 2 | Texas |
| 3 | Washington |
| 4 | South Dakota |
| 5 | Alaska |
| 6 | Ohio |
+-------+--------------+
user_jurisdiction
userID (Foriegn Key pointing to employees userID)
jurID (Foriegn Key pointing to jurisdictions jurID)
records:
+--------+-------+
| userID | jurID |
+--------+-------+
| 6 | 2 |
| 6 | 3 |
| 11 | 2 |
+--------+-------+
我想让它在删除父表行的地方,带有相应外键的中间表将被自动删除。 我用以下方法制作了中间表:
CREATE TABLE user_jurisdiction(userID int NOT NULL, jurID int NOT NULL, FOREIGN KEY(userID) REFERENCES employee(userID) ON DELETE CASCADE, FOREIGN KEY (jurID) REFERENCES jurisdictions(jurID) ON DELETE CASCADE);
但是,当我从父表中删除某项内容时……就像表jurisidictions.jurisdiction中的州名行一样,userID和jurID行不会自动从中间表user_jurisdiction中删除。 从我所看到的,我对每个外键都正确地进行了DELETE ON CASCADE。 当删除父表行时,为什么中间表中没有删除带有外键的对应行?
最可能的原因是您使用的是MyISAM引擎而不是INNODB引擎。 MyISAM引擎解析外键约束,但不强制执行。
CREATE TABLE user_jurisdiction(
userID int NOT NULL,
jurID int NOT NULL,
FOREIGN KEY(userID)
REFERENCES employee(userID) ON DELETE CASCADE,
FOREIGN KEY (jurID)
REFERENCES jurisdictions(jurID) ON DELETE CASCADE
) ENGINE=INNODB;
从5.5版开始,INNODB是MySQL的默认存储引擎。 在此之前,默认是MyISAM。
养成张贴SQL DDL而不是(或与之相关的)表描述的习惯。 DDL比描述准确得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.