我有两个表:IDCa和IDCb.At开头,每个表都有数据并且工作正常。表IDCb具有带有IDCa的主键sheetNum的外键sheetNum。
当我将IDCa重命名为IDCabk并删除IDCa时,它失败了。 所以我跑了:set foreign_key_checks = 0 ,删除表IDCa,创建IDCabk之类的表IDC。
现在IDCa是空的。之后,我发现IDCb的REFERENCES表已从IDCa更改为IDCabk。所以我删掉IDCb外键,并读取如下:
alter table IDCb add constraint fk_dvcOnsh foreign key (sheetNum) references IDCa(sheetNum);
运行后:设置foreign_key_checks = 1,并尝试插入数据。但不幸的是,它运行失败。似乎没有错。
这里有IDCa信息,运行:show create table IDCa:
|IDCa | CREATE TABLE `IDCa` (
`sheetNum` int(255) NOT NULL AUTO_INCREMENT,
.........
PRIMARY KEY (`sheetNum`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
这里有IDCb信息,运行:show create table IDCb:
|IDCb | CREATE TABLE `IDCb` (
`id` int(255) NOT NULL AUTO_INCREMENT,
......
`sheetNum` int(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_dvcOnsh` (`sheetNum`),
CONSTRAINT `fk_dvcOnsh` FOREIGN KEY (`sheetNum`) REFERENCES `IDCa` (`sheetnum`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8
我的数据插入代码:
$conn->beginTransaction();
$query="insert into IDCa(xxx) values('aaa')";
$stmt=$conn->query($query);
$stmt->closeCursor();
$query="insert into IDCb(rrr,sheetNum) values('aaa',LAST_INSERT_ID())";
$stmt=$conn->query($query);
$stmt->closeCursor();
$conn->commit();
显示错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`hpc`.`IDCb`, CONSTRAINT `fk_dvcOnsh` FOREIGN KEY (`sheetnum`) REFERENCES `IDCa` (`sheetnum`))fail