我有一个奇怪的问题,我正在尝试将一个外键添加到一个引用另一个的表,但由于某种原因它失败了。由于我对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')
答案 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 )
换句话说,你试图在一个不存在的部门创建一张床。