MySQL Create table with indexes error

database-design, mysql, mysql-error-1005

Solution

"errno 121 means a duplicate key error"

Constraints must have an unique name in the database, you might wanna change your FK names. Like so, `FK_groupMembers_group` and `FK_groupMembers_user`.

Problem

Ok, so I am creating tables in MySQL with indexes and foreign keys. I use MySQL Workbench to create the tables and then have it forward engineer a SQL create script (I do better in a visual DB environment than just writing out the SQL code by hand right away). The problem is many times when I import the sql script into mysql, I get the classic eror: ``` #1005 - Can't create table 'db.tablename' (errno: 121) ``` I've managed to figure out the problem each time, usually index/foreign key related, but now I'm starting to get irritated at having to fix it each time. I don't really understand what the problem is (especially when a MySQL product is creating sql code for its own database). Below is some code that typically causes the problem. ``` CREATE TABLE IF NOT EXISTS `db`.`groupMembers` ( `groupMembersID` INT NOT NULL AUTO_INCREMENT , `groupID` INT NOT NULL , `userID` INT NULL , PRIMARY KEY (`groupMembersID`) , INDEX `group` (`groupID` ASC) , INDEX `user` (`userID` ASC) , CONSTRAINT `group` FOREIGN KEY (`groupID` ) REFERENCES `db`.`groups` (`groupsID` ) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `user` FOREIGN KEY (`userID` ) REFERENCES `db`.`users` (`usersID` ) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = InnoDB; ``` The error usually comes from the first INDEX definition - even when I take out the index definition, I just get the error at the the first foreign key constraint definition. I've checked, and the foreign key remote column and the local column are the same data-type and size.

Original source