Question


-- Table Project_DB.Product_table


CREATE TABLE IF NOT EXISTS  `Project_DB`.`Product_table`
(
    `Product_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
    `User_id_fk` INT UNSIGNED NOT NULL ,
    `Product_Category_id` INT UNSIGNED NOT NULL ,
    `Product_Name` VARCHAR( 45 ) NOT NULL ,
    `Product_Price` INT UNSIGNED NOT NULL ,
    `Product_details` MEDIUMTEXT NULL ,
    PRIMARY KEY (  `Product_id` ) ,
    INDEX  `User_id_idx` (  `User_id_fk` ASC ) ,
    CONSTRAINT  `User_id` FOREIGN KEY (  `User_id_fk` )
        REFERENCES `Project_DB`.`Registration_table` ( `User_id` )
        ON DELETE NO ACTION ON UPDATE NO ACTION

) ENGINE = INNODB;

MySQL said: Documentation

#1022 - Can't write; duplicate key in table 'product_table'

Was it helpful?

Solution

The Database Schema Cannot have two or more FOREIGN KEY with same name. I change all FOREIGN KEYS to different names in my DB Schema then it works...

OTHER TIPS

I recommend you try removing the line

INDEX  `User_id_idx` (  `User_id_fk` ASC ) ,

Either that, or remove the foreign key constraint from the table definition, and add that in a separate ALTER TABLE statement.

InnoDB automatically creates the required index when a foreign key constraint is added, or uses a suitable index if it's already there.

I believe the error is occurring because InnoDB is attempting to create an index for the foreign key, rather than using the index that was defined previously. That is, when the CREATE TABLE statement (as posted by OP) is processed, InnoDB is attempting to create both the index defined on User_id_fk, and the index required for the foreign key.

And those two indexes are "duplicates" of each other.

The workaround is to modify the CREATE TABLE statement, to avoid InnoDB attempting to create "duplicate" indexes.

I had the same problem, MySQLWorkbench was working fine when I forward engineered a build script and then it decided to throw it's toys out of the pram.

I fixed the problem by dropping my database in phpMyAdmin and then ran the script again from MySQLWorkbench and it worked. I suspect I'd changed something that caused a conflict.

I know this is an extreme measure; others have said, to go through the DB schema and find duplicates.

Usually, you already use that constraint in another table that you also use for foreign key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top