Search code examples
mysqlforeign-keysconstraintspercona

MySQL: Duplicate Key Error 1022 for non duplicate key


I'm trying to create a table with different foreign key constraints but mysql complains about this DDL:

CREATE TABLE tasks (
        id INTEGER NOT NULL AUTO_INCREMENT, 
        `createdAt` DATETIME NOT NULL DEFAULT now(), 
        `updatedAt` DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW(), 
        `createdBy_user_id` INTEGER NOT NULL, 
        `updatedBy_user_id` INTEGER NOT NULL, 
        status ENUM('open','closed') NOT NULL, 
        customer_id INTEGER NOT NULL, 
        `projectDescription` TEXT, 
        PRIMARY KEY (id), 
        CONSTRAINT user_id_fk FOREIGN KEY(`createdBy_user_id`) REFERENCES users (id), 
        CONSTRAINT customer_id_fk FOREIGN KEY(customer_id) REFERENCES `Customer` (id), 
        CONSTRAINT user_up_id_fk FOREIGN KEY(`updatedBy_user_id`) REFERENCES users (id)
)COLLATE utf8mb4_german2_ci CHARSET=utf8mb4

I get the error ERROR 1022 (23000): Can't write; duplicate key in table 'tasks' that makes no sense because every constraint has a different name and is applied on different columns.

Strangely MySQL does not complain if i remove the fk-suffix and replace it by something like constr.

Does anybode know why MySQL 5.7 (Server version: 5.7.30-33 Percona Server (GPL), Release 33, Revision 6517692) behaves like this?


Solution

  • You have used a constraint with the same name in another table.

    This is a way to reproduce easily this problem :

    CREATE TABLE foo
    (
      id int not null auto_increment primary key
    );
    
    CREATE TABLE bar
    (
      id int not null auto_increment primary key,
      foo_id int,
      
      CONSTRAINT foo_id_fk FOREIGN KEY(`foo_id`) REFERENCES foo(id) -- <- Check this constraint name
    );
    
    CREATE TABLE hello
    (
      id int not null auto_increment primary key,
      foo_id int,
      
      CONSTRAINT foo_id_fk FOREIGN KEY(`foo_id`) REFERENCES foo(id) -- <-- same constraint name than before
    );
    

    Schema Error: Error: ER_DUP_KEY: Can't write; duplicate key in table 'hello'

    To fix this, make sure the FK names are unique. You can ommit the naming of constraints, so MySQL will create one for you.

    --        v----------- no name here
    CONSTRAINT FOREIGN KEY(`createdBy_user_id`) REFERENCES users (id)
    

    Or you can use a naming convention