Errno 121, duplicate key on write or update?

This answer comes from the comment to the answer from @Michael Berkowski. I post it as an answer as it actually worked for me:

I was getting the errno 121 even after changing the constraint names across multiple tables. The problem was that even across different tables you cannot have the same constraint name. I was using fk_entryid in table1 and table2 and had to change them to fk_table1_entryid and fk_table2_entryid respectively to make it work.


All the answers above are superb but didn't solve my problem even after i dropped all my tables, but everything worked perfectly and the migration ran smoothly after i dropped my DB and created it again.... It seems the keys are cached and aren't cleared after tables are dropped.

Note : This is not an answer to the question but my experience that i felt might help another person.


This is likely because you have named at least one constraint with the same identifier as a column:

/* You already have a column named `restaurant` in this table, 
   but are naming the FK CONSTRAINT `restaurant` also... */
CONSTRAINT `restaurant`
    FOREIGN KEY (`restaurant` )
    REFERENCES `mydb`.`restaurants` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

Should use a different identifier for the constraint like fk_restaurant as in :

CONSTRAINT `fk_restaurant`
    FOREIGN KEY (`restaurant` )
    REFERENCES `mydb`.`restaurants` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

And same thing in the food table:

  /* Name it fk_food */
  CONSTRAINT `fk_food`
    FOREIGN KEY (`food` )
    REFERENCES `mydb`.`food` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  /* Name it fk_restaurant */
  CONSTRAINT `fk_restaurant`
    FOREIGN KEY (`restaurant` )
    REFERENCES `mydb`.`restaurants` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

Those are the only three I see, but there could be others I missed.