2012-08-24 80 views
4

我有一個奇怪的問題,我試圖添加一個外鍵引用另一個表,但它由於某種原因失敗。由於我對MySQL的知識有限,唯一可能會懷疑的是在引用我想引用的表的不同表上有一個外鍵。錯誤1452:無法添加或更新子行

這裏是我的表關係的照片,通過工作臺產生的:關係

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

+2

請確保您在「department」表中具有「Department_Id = 4555」的條目。 – Omesh

回答

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) 

告訴您,您插入的行對於您插入列depId(如Omesh指出的)中的值的department/department_id需要相應的值。最重要的一點是在這裏:

DEPID)參考系(DEPARTMENT_ID

換句話說,你已經嘗試在一個不存在的部門創建一張牀。

相關問題