#1452 - Cannot add or update a child row: a foreign key constraint fails

10,606

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.

Share:
10,606
Muhammad Yawar
Author by

Muhammad Yawar

Updated on June 05, 2022

Comments

  • Muhammad Yawar
    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 and employee_id is the FK references to employees table PK employee_id.

    Now, i am creating fine_id (column in table employees) as a FK reference to fine_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, CONSTRAINT fine_fk FOREIGN KEY (fine_id) REFERENCES fines (fine_id) ON DELETE CASCADE ON UPDATE CASCADE)

    Here are attached images:

    employees table

    enter image description here

    fines table

    enter image description here

    error

    enter image description here

    Thanks.

  • Eyad Mohammed Osama
    Eyad Mohammed Osama over 3 years
    Since i had the exact same problem, i would like to suggest truncating the table before trying to add the constraint, this worked for me