janlindso
janlindso

Reputation: 1239

INSERT-statement with foreign key

I'm trying to INSERT into a table, but I get the error Cannot add or update a child row: a foreign key contraint fails.

And as the error says, I have a foreign key I'm trying to update.

Right now I'm using a simple INSERT like:

INSERT INTO tblTable1 (firstColumn, foreignKey) VALUES ('blabla', 1)

How can I insert this if foreignKey is the id of tblTable2?

Upvotes: 1

Views: 2258

Answers (3)

Marcus Adams
Marcus Adams

Reputation: 53830

You need to add the record to the parent table first, then the child table.

From MySQL documentation on foreign key constraints:

InnoDB rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table.

Here's MySQL documentation of how to use foreign key constraints and examples.

Upvotes: 3

Rizstien
Rizstien

Reputation: 802

first insert that entry on which u applied foreign key constraint in Table2 then add run insert query in Table1. it will work

Upvotes: 2

Łukasz W.
Łukasz W.

Reputation: 9755

You have to keep your constaints. You cannot add record that does not have suitable value in related table!

Upvotes: 2

Related Questions