简体   繁体   中英

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

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

在此处输入图像描述

fines table

在此处输入图像描述

error

在此处输入图像描述

Thanks.

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.

I will suggest to use query to set foreign key. Not graphically. That worked for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM