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

10.6k Views Asked by At

I'm trying to set up a simple database for an online shopping webpage. But there are problems with my database.

So in my ERD diagram where I've linked my category table to my main_course table as each main course will have a category like Japanese food or Italian food etc.

I've exported my sql from this ERD to my database but when i insert a record it shows me this:

#1452 - Cannot add or update a child row: a foreign key constraint fails (fyp.main_course, CONSTRAINT fk_main_course_category1 FOREIGN KEY (category_id) REFERENCES category (category_id) ON DELETE NO ACTION ON UPDATE NO ACTION)

I can't seem to figure out. Anybody help?

2

There are 2 best solutions below

0
On

You're trying to insert a record in main_course, but the category_id you're trying to insert doesn't exist in category. You need to insert it there first.

0
On

At the time of creating this parent-child tables in your database, the child create table statement referenced parent table field category_id to establish the constraint. And, as before you inserted data into parent table, you've tried to insert data into child table, DBMS restricts you to insert. Insert data into parent table first, then insert into child table.