0

Every time I'm trying to insert a foreign key to the table I got that message:

Error Code: 1215. Cannot add foreign key constraint 0.281 sec

My create table code:

CREATE TABLE `test`.`buy`(
    `id` INT NOT NULL AUTO_INCREMENT,
    `id_customer` INT UNSIGNED NOT NULL,
    `code` VARCHAR(45) NOT NULL,
    PRIMARY KEY(`id`),
    UNIQUE INDEX `code_UNIQUE`(`code`),
    CONSTRAINT `id_customer` FOREIGN KEY(`id_customer`) REFERENCES `test`.`customer`(`id_customer`) ON DELETE RESTRICT ON UPDATE CASCADE,
    CONSTRAINT `code` FOREIGN KEY(`code`) REFERENCES `test`.`product`(`code`) ON DELETE RESTRICT ON UPDATE CASCADE
)

What should I do ?

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
BlackAndWhite
  • 55
  • 2
  • 9
  • Look at this answer: http://stackoverflow.com/questions/17691282/error-code-1215-cannot-add-foreign-key-constraint-foreign-keys#answer-17691401 – Moshe Harush May 14 '17 at 00:46

1 Answers1

0

Please format your code next time so it's easier to read.

You don't need the CONSTRAINT xxx bit, try this instead:

CREATE TABLE test.buy (
  id INT NOT NULL AUTO_INCREMENT,
  id_customer INT UNSIGNED NOT NULL,
  code VARCHAR(45) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE INDEX code_UNIQUE (code),
  FOREIGN KEY (id_customer) 
    REFERENCES test.customer (id_customer) 
    ON DELETE RESTRICT ON UPDATE CASCADE,
  FOREIGN KEY (code) 
    REFERENCES test.product (code) 
    ON DELETE RESTRICT ON UPDATE CASCADE
);

If that still doesn't work then make sure the other tables you reference (test.customer and test.product) already exist and that they have matching fields of the same data type.