0

I recently moved some tables to a new database. I left the foreign keys of these tables pointing to tables in the old DB.

I then created new versions of the referenced tables. I tried first to modify the FK so that they will point to the new references. That didn't work, so I dropped all old FKs and tried to create new ones. The first phase went through without a hitch. The second phase though failed with each and every table, in the same way! The response was always like:

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`ml`.`#sql-d04_2`, CONSTRAINT `FK_excoeff_secID` FOREIGN KEY (`SecurityID`) REFERENCES `securities` (`SecurityID`))    

The failure appears immediately and doesn't seem to relate to actual data. In the error message, as you can see, the place where the table name is usually located is now filled with a strange string. And no matter what the referring table is, the error contains the same string.

All that happend in the "Alter table" part of the MySQL WorkBench, but also as a regular SQL query.

Where did I go wrong???

MeirG
  • 333
  • 2
  • 14
  • Possible duplicate of http://stackoverflow.com/questions/21659691/error-1452-cannot-add-or-update-a-child-row-a-foreign-key-constraint-fails – Kiran Kumar Dec 25 '16 at 16:52
  • No, it is not. The key differences are 1) the strange string where the table name is. It must mean something, and 2) it is the _same_ "table name" for all tables that I try to add a FK to them. 3) All table data _was_ governed by an equivalent foreign-key. There are no conflicts in the data! – MeirG Dec 26 '16 at 06:52

1 Answers1

0

Mr. Peter Brawly, in the MySQL forums was very helpful. His answer was:

  1. The "strange string" was simply the name of a temporary table used internally
  2. The reason for the failure is probably the old fashion one - a violation of the referential integrity in the data. And he was right!
  3. And the SQL query to detect the culprit(s) is:

    SELECT DISTINCT c.ID FROM child_table AS c LEFT JOIN parent_table AS p USING(ID) WHERE p.ID IS NULL;

MeirG
  • 333
  • 2
  • 14