2

I have a new table that has a foreign key constraint to an old, legacy table. The old table is populated with a great deal of data, but when I try to add a row to the new table that references a row in the old table, I get a Cannot add or update a child row: a foreign key constraint fails error.

How do I add rows to the new table that reference rows in the old table?

EDIT Here are two queries I tried:

mysql> select user_pk from users where username = 'test_user';
+---------+
| user_pk |
+---------+
|  123766 |
+---------+
1 row in set (0.00 sec)

mysql> insert into uservisit (user_id) values (123766);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test_database`.`uservisit`, CONSTRAINT `user_id_refs_user_pk_37c3999c` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_pk`))

Am I doing something wrong?

exupero
  • 9,136
  • 8
  • 47
  • 63
  • 1
    You're sure the value you're trying to insert into the new table exists in the old table? – Joe Stefanelli Mar 10 '11 at 17:50
  • See if the comments here answer your question: http://stackoverflow.com/questions/1253459/mysql-error-1452-cannot-add-or-update-a-child-row-a-foreign-key-constraint-fai – Raelshark Mar 10 '11 at 17:50

3 Answers3

4

You can temporary disable foreign key checks like so:

SET foreign_key_checks = 0;
...
do updates
...
SET foreign_key_checks = 1;

Better make sure that after all your updates everything is in order foreign key-wise though.

Johan
  • 74,508
  • 24
  • 191
  • 319
0

When you insert your new row, the value you put in the column with the foreign key must also exist in the referenced column in the old table.

Maybe if you past some queries and example data, it would be easier to help.

krtek
  • 26,334
  • 5
  • 56
  • 84
0

If you are using a version of MySQL prior to 5.5.13 you may be running into this bug:
MySQL 5.5 foreign key constraint fails when foreign key exists

Community
  • 1
  • 1
penfold
  • 1,523
  • 1
  • 14
  • 21