错误1452:不能添加或更新子行(ERROR 1452: Cannot add or update

2019-09-21 14:38发布

我有一点奇怪的问题,我想一个外键添加到引用另外一个表,但它失败的某些原因。 用我有限的MySQL的知识,这也可能会被犯罪嫌疑人的唯一的事情是,有一个不同的表的外键引用一个我想引用。

这里是我的表关系,通过工作台生成的图片:关系

CREATE TABLE `beds` (
  `bedId` int(11) NOT NULL,
  `wardId` int(11) DEFAULT NULL,
  `depId` int(11) DEFAULT NULL,
  `desc` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`bedId`),
  KEY `departmentId_idx` (`depId`),
  KEY `wardId_idx` (`wardId`),
  CONSTRAINT `departmentId` FOREIGN KEY (`depId`) 
     REFERENCES `department` (`Department_Id`) 
     ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `wardId` FOREIGN KEY (`wardId`) REFERENCES `wards` (`wardId`) 
     ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(`asiahospitaldb`.`beds`, CONSTRAINT `departmentId` FOREIGN KEY (`depId`) 
REFERENCES `department` (`Department_Id`) 
ON DELETE NO ACTION ON UPDATE NO ACTION)

SQL Statement:

INSERT INTO `asiahospitaldb`.`Beds` (`bedId`, `wardId`, `depId`, `desc`) 
VALUES ('456', '7444', '4555', 'ikiuj')

Answer 1:

这个

ERROR 1452: Cannot add or update a child row: a foreign key constraint
fails (`asiahospitaldb`.`beds`, CONSTRAINT `departmentId` FOREIGN KEY
(`depId`)  REFERENCES `department` (`Department_Id`)  ON DELETE NO
`enter code here`ACTION ON UPDATE NO ACTION)

告诉你,你已经插入的行预计,相应的数值department/department_id为已插入到列中的值depId (如Omesh指出)。 最重要的一点是在这里:

(DEPID)参考部门( 部门标识

换句话说,你已经尝试在一个不存在的部门创建一张床。



文章来源: ERROR 1452: Cannot add or update a child row