I am trying to insert values into the employee table but when I tried to execute the script, it gave me this error. What am I doing wrong?
RESPONSE:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (
smolcompany
.employee
, CONSTRAINTemployee_fk2
FOREIGN KEY (DeptID
) REFERENCESdepartment
(DeptID
) ON DELETE RESTRICT ON UPDATE CASCADE)
ACTION:
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;
VALUES:
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);
I found the problem, I had to add the constraint
ALTER TABLE employee ADD CONSTRAINT employee_fk2 FOREIGN KEY(DeptID) REFERENCES department(DeptID) ON UPDATE CASCADE ON DELETE RESTRICT;
only after I had created both tables and inserted all the values. Thank you everyone for your suggestions.