简体   繁体   中英

MySQL: Cannot add a foreign key

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???

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM