Reputation: 267049
I have a column contactId
on one table which is a foreign key, connected to the id of contacts
table. I.e, every row in my 2nd table can be connected to a contact.
However, some records don't have to be connected to any contacts. In such cases, the contact Id would be 0. When I try to insert such a record, I get this error:
Error Number: 1452 Cannot add or update a child row: a foreign key constraint fails
What should I do?
Upvotes: 2
Views: 162
Reputation: 31406
If the column contactId
that has the FK to the other table is nullable (and it can be) you should be able to just set those that don't have any contacts to NULL
. A foreign key basically means that if the column has a non-NULL value, then that value has to exist in the primary key of the table referenced by the foreign key constraint. Otherwise, just set it to NULL.
Upvotes: 3
Reputation: 562230
Use NULL as the contactId
when it's irrelevant that the row reference a concact.
Foreign key columns can be nullable.
Upvotes: 2