MySQL: Creating table with two foreign keys fails with "Duplicate key name" error

Try making the FK names distinct:

CREATE TABLE Products (
    id INT NOT NULL,
    PRIMARY KEY(id)
);

CREATE TABLE WarehouseMovements (
    time        DATETIME           NOT NULL,
    product1    INT                NOT NULL,
    product2    INT                NOT NULL,

    FOREIGN KEY IX_WarehouseMovements_product1(product1) REFERENCES Products(id),
    FOREIGN KEY IX_WarehouseMovements_product2(product2) REFERENCES Products(id)
);

UPDATE

That's an index or FK name, not a table name. See create-table-foreign-keys documentation:

[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)

Which says

index_name represents a foreign key ID. If given, this is ignored if an index for the foreign key is defined explicitly. Otherwise, if MySQL creates an index for the foreign key, it uses index_name for the index name.


you must to add constraint with different names to FK

CREATE TABLE Products (
    id INT NOT NULL,
    PRIMARY KEY (id)
);

CREATE TABLE WarehouseMovements (
    time DATETIME NOT NULL,
    product1 INT NOT NULL,
    product2 INT NOT NULL,
    CONSTRAINT fk_product_1 FOREIGN KEY (product1) REFERENCES Products (id),
    CONSTRAINT fk_product_2 FOREIGN KEY (product2) REFERENCES Products (id)
);

Tags:

Mysql

Sql