13

While trying to create a new table, MySQL is giving me an error I cannot explain.

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 WarehouseMovements(product1) REFERENCES Products(id),
    FOREIGN KEY WarehouseMovements(product2) REFERENCES Products(id)
);

This fails with ERROR 1061 (42000): Duplicate key name 'WarehouseMovements'. If I remove the foreign key constraints this succeeds, but I want to make sure product1 and product2 are actually pointing to somewhere.

Default engine is InnoDB.

What's wrong with the query?

3 Answers 3

13

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.

2
  • 1
    I was under the impression I was supposed to put the table name before the parentheses... Huh. Thanks! This worked. May 22, 2013 at 19:29
  • @GiorgosBitzes I added a reference where the syntax is described. There are a couple way to do this. You'll also see FK_ name prefixes. May 22, 2013 at 19:38
6

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)
);
0
ALTER TABLE `cca_orders` 
ADD  CONSTRAINT `item_id` 
FOREIGN KEY (`item_id`) 
REFERENCES `joshi_textile_db`.`cca_items_master`(`id`) 
ON DELETE RESTRICT 
ON UPDATE RESTRICT;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.