4

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

关系

4

1 回答 1

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 ) 参考部门 ( Department_Id )

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

于 2012-08-24T07:31:57.420 回答