简体   繁体   English

MySQL外键级联删除不起作用,完全陷入困境

[英]MySQL foreign key cascade delete not working, completely stumped

I have read a bunch of other threads on this but I am still stumped. 我已经读过很多其他主题,但是我仍然很困惑。 I have created a two very simple tables as a sanity check and unable to get them to preform a cascade delete so need some help at this point. 我已经创建了两个非常简单的表来进行完整性检查,并且无法让它们执行级联删除,因此在这一点上需要一些帮助。

CREATE TABLE `test1` (
  `test1_ID` int(11) NOT NULL AUTO_INCREMENT,
  `test1_name` char(15) DEFAULT NULL,
  PRIMARY KEY (`test1_ID`),
  UNIQUE KEY `test1_ID_UNIQUE` (`test1_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `test2` (
  `test2_ID` int(11) NOT NULL AUTO_INCREMENT,
  `test2_FK_test1` int(11) NOT NULL,
  `test2_name` char(15) DEFAULT NULL,
  PRIMARY KEY (`test2_ID`),
  UNIQUE KEY `test2_ID_UNIQUE` (`test2_ID`),
  KEY `IDX_test2_FK_test1` (`test2_FK_test1`),
  CONSTRAINT `FK_test2__test1` FOREIGN KEY (`test2_FK_test1`) REFERENCES `test1` (`test1_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table data used for testing 用于测试的表数据

Test 1 Table Data:
+----------+------------+
| test1_ID | test1_name |
+----------+------------+
|        1 | test1 r1   |
|        2 | test1 r2   |
+----------+------------+

Test 2 Table Data:
+----------+----------------+----------------+
| test2_ID | test2_FK_test1 | test2_name     |
+----------+----------------+----------------+
|        1 |              1 | Test2 R1 - FK1 |
|        2 |              1 | Test2 R2 - FK1 |
|        3 |              1 | Test2 R3 - FK1 |
+----------+----------------+----------------+

Insert statements:
INSERT INTO `test1` VALUES (1,'test1 r2'),(2,'test1 r2');
INSERT INTO `test2` VALUES (1,1,'Test2 R1 - FK1'),(2,1,'Test2 R2 - FK1'),(3,1,'Test2 R3 - FK1');

If I delete the first row from the test1 table nothing happens to the test2 table data 如果我从test1表中删除第一行,则test2表数据没有任何反应

DELETE FROM test1 WHERE test1_ID = 1;

It turned out to be a bug in the version of MySQL I was using, 5.5.28. 原来是我使用的MySQL版本5.5.28中的一个错误。 I just upgraded to 5.6.13 and everything works now. 我刚刚升级到5.6.13,现在一切正常。 Thanks for the help. 谢谢您的帮助。

Make sure mysql "foreign key checks" is enabled: 确保启用了mysql“外键检查”:

select @@FOREIGN_KEY_CHECKS;

set FOREIGN_KEY_CHECKS=1;

I've found that calling PDO::exec('SET FOREIGN_KEY_CHECKS=1') is necessary for PDO to respect ON DELETE and ON UPDATE actions. 我发现,调用PDO::exec('SET FOREIGN_KEY_CHECKS=1')对于PDO而言必须遵循ON DELETEON UPDATE动作。 For some reason, foreign key constraints are disabled by default on my system. 由于某些原因,默认情况下,我的系统上禁用外键约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM