错误1452:无法添加或更新子行

时间:2012-08-24 07:02:49

标签: mysql sql database jsp foreign-keys

我有一个奇怪的问题,我正在尝试将一个外键添加到一个引用另一个的表,但由于某种原因它失败了。由于我对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')

Relationship

1 个答案:

答案 0 :(得分: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 )REFERENCES部门( Department_Id

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