MySQL 错误代码:1452。无法添加或更新子行:外键约束失败

MySQL Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails

我正在尝试向员工中插入值 table 但是当我尝试执行脚本时,它给了我这个错误。我做错了什么?

响应:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (smolcompany.employee, CONSTRAINT employee_fk2 FOREIGN KEY (DeptID) REFERENCES department (DeptID) ON DELETE RESTRICT ON UPDATE CASCADE)

操作:

INSERT INTO employee VALUES (4283, 'Sarim Mansoor', 'M', 27, 'Mont Kiara', NULL, 102), (4465, 'Teh Yi Heng', 'M', 23, 'Cyberjaya', NULL, 101), (4123, 'Thamal Kishen', 'F', 47, 'Petaling Jaya', 4283, 102), (3978, 'Mike Ross', 'M', 26, 'Mont Kiara', NULL, 103), (5240, 'Martha Arnold', 'F', 27, 'Mont Kiara', 4465, 101)

TABLE:

CREATE TABLE employee 
(
EmpID INT NOT NULL,
EmpName VARCHAR(50) NOT NULL,
EmpGender CHAR(1) NOT NULL,
EmpAge INT NOT NULL,
EmpAddress VARCHAR(50) NOT NULL,
SuperID INT,
DeptID INT NOT NULL,
CONSTRAINT employee_pk PRIMARY KEY(EmpID),
CONSTRAINT employee_uk UNIQUE(EmpName),
CONSTRAINT employee_ck CHECK(EmpAge>18 AND EmpAge<100),
CONSTRAINT employee_fk1 FOREIGN KEY(SuperID) REFERENCES employee(EmpID) ON UPDATE CASCADE ON DELETE RESTRICT
);

CREATE TABLE department 
(
DeptID INT NOT NULL,
DeptName VARCHAR(50) NOT NULL,
DeptBlock CHAR(1) NOT NULL,
DeptLevel INT NOT NULL,
ManagerID INT NOT NULL,
MStartDate DATE NOT NULL,
CONSTRAINT department_pk PRIMARY KEY(DeptID),
CONSTRAINT department_uk UNIQUE(DeptName),
CONSTRAINT department_ck CHECK(DeptBlock='A' OR DeptBlock='B' OR DeptBlock='C'),
CONSTRAINT department_fk FOREIGN KEY(ManagerID) REFERENCES employee(EmpID) ON UPDATE CASCADE ON DELETE RESTRICT
);

ALTER TABLE employee ADD CONSTRAINT employee_fk2 FOREIGN KEY(DeptID) REFERENCES department(DeptID) ON UPDATE CASCADE ON DELETE RESTRICT;

值:

INSERT INTO employee 
VALUES
(4283, 'Sarim Mansoor', 'M', 27, 'Mont Kiara', NULL, 102),
(4465, 'Teh Yi Heng', 'M', 23, 'Cyberjaya', NULL, 101),
(4123, 'Thamal Kishen', 'F', 47, 'Petaling Jaya', 4283, 102),
(3978, 'Mike Ross', 'M', 26, 'Mont Kiara', NULL, 103),
(5240, 'Martha Arnold', 'F', 27, 'Mont Kiara', 4465, 101);

我发现了问题,我不得不添加约束

ALTER TABLE employee ADD CONSTRAINT employee_fk2 FOREIGN KEY(DeptID) REFERENCES department(DeptID) ON UPDATE CASCADE ON DELETE RESTRICT;

仅在我创建了两个表并插入了所有值之后。谢谢大家的建议。