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?
If the column
contactIdthat 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 toNULL. 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.