Errno 121, duplicate key on write or update?

后端 未结 4 744
既然无缘
既然无缘 2020-12-07 00:36
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MO         


        
相关标签:
4条回答
  • 2020-12-07 01:02

    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.

    0 讨论(0)
  • 2020-12-07 01:06

    This is kind of a response to @peter-moses, as I had exactly the same issues as he did.

    I solved that problem by adding --add-drop-database to my dump command. Its documented here: https://mariadb.com/kb/en/mysqldump/

    My final command looks like this:

    mysqldump -uroot -ppassword --single-transaction --all-databases --add-drop-database

    0 讨论(0)
  • 2020-12-07 01:08

    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.

    0 讨论(0)
  • 2020-12-07 01:15

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题