ERROR 1452: Cannot add or update a child row

2019-06-24 08:14发布

问题:

I'm having a bit of a strange problem, I'm trying to add a foreign key to one table that references another, but it is failing for some reason. With my limited knowledge of MySQL, the only thing that could possibly be suspect is that there is a foreign key on a different table referencing the one I am trying to reference.

Here is a picture of my table relationships, generated via workbench: Relationships

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')

回答1:

This

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)

is telling you that the row you have inserted expects a corresponding value for department/department_id for the value you have inserted into column depId (as Omesh pointed out). The important bit is here:

(depId) REFERENCES department (Department_Id)

In other words, you have tried to create a bed in a non-existent department.