#1452 - Cannot add or update a child row: a foreign key constraint fails
somehow i managed to solve my issue myself,
the problem was that in my employees table i have the column fine_id
which i want to make a FK, that column value was empty in my existing record in employees table, although i have values in my fines table, but the column fine_id
in employees table was not filled, with the corresponding fine_id
of fines table, so before creating FK i have filled my column with the correct ID's of fines table, and my problem was gone away.
Muhammad Yawar
Updated on June 05, 2022Comments
-
Muhammad Yawar almost 2 years
NOTE: Before marking it as Duplicate, i want to tell you guys that i've gone through all these related problems in stackoverflow and other websites, but i didn't get any suitable solution, so that's why i am here for the help.
I have two tables: employees and fines
In fines table
fine_id
is the PK andemployee_id
is the FK references to employees table PKemployee_id
.Now, i am creating
fine_id
(column in table employees) as a FK reference tofine_id
in fines table.i am adding constraints via XAMPP PHPMYADMIN it auto generates my query which is:
ALTER TABLE employees ADD CONSTRAINT fine_fk FOREIGN KEY (fine_id) REFERENCES fines(fine_id) ON DELETE CASCADE ON UPDATE CASCADE;
But, I am getting this error while running this
SQL Query
1452 - Cannot add or update a child row: a foreign key constraint fails (
ems_db
.#sql-dd4_35
, CONSTRAINTfine_fk
FOREIGN KEY (fine_id
) REFERENCESfines
(fine_id
) ON DELETE CASCADE ON UPDATE CASCADE)Here are attached images:
employees table
fines table
error
Thanks.
-
Eyad Mohammed Osama over 3 yearsSince i had the exact same problem, i would like to suggest truncating the table before trying to add the constraint, this worked for me