外键错误1215

时间:2013-10-05 13:58:34

标签: mysql

我收到了

  

错误代码1215无法添加外键约束。

当我离开时FOREIGN KEY (product_id) REFERENCES products(product_id) 在代码中它似乎工作,但当我添加它时,我收到错误。

CREATE SCHEMA `my_web_db`;

USE my_web_db;

DROP TABLE IF EXISTS USERS;
DROP TABLE IF EXISTS DOWNLOADS;
DROP TABLE IF EXISTS PRODUCTS;

CREATE  TABLE `my_web_db`.`USERS` (
  `user_id` INT NOT NULL ,
  `email_address` VARCHAR(100) NULL ,
  `first_name` VARCHAR(45) NULL ,
  `last_name` VARCHAR(45) NULL ,
   PRIMARY KEY (`user_id`) )
DEFAULT CHARACTER SET = utf8;

CREATE  TABLE `my_web_db`.`DOWNLOADS` (
  `download_id` INT NOT NULL ,
  `user_id` INT ,
  `download_date` DATETIME NULL ,
  `filename` VARCHAR(45) NULL ,
  `product_id` INT NOT NULL,
  PRIMARY KEY (`download_id`),
  FOREIGN KEY (user_id) REFERENCES users(user_id),
  FOREIGN KEY (product_id) REFERENCES products(product_id)
)
DEFAULT CHARACTER SET = utf8;

CREATE  TABLE `my_web_db`.`PRODUCTS` (
  `product_id` INT NOT NULL ,
  `product_name` VARCHAR(45) NULL ,
  PRIMARY KEY (`product_id`)
)
DEFAULT CHARACTER SET = utf8;

1 个答案:

答案 0 :(得分:0)

我认为您使用的是ENGINE = myisam,您应该使用ENGINE = InnoDB来创建外键引用。

添加了ENGINE类型。 更新了SQL:

CREATE  TABLE `my_web_db`.`USERS` (
  `user_id` INT NOT NULL ,
  `email_address` VARCHAR(100) NULL ,
  `first_name` VARCHAR(45) NULL ,
  `last_name` VARCHAR(45) NULL ,
   PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8;

CREATE  TABLE `my_web_db`.`PRODUCTS` (
  `product_id` INT NOT NULL ,
  `product_name` VARCHAR(45) NULL ,
  PRIMARY KEY (`product_id`)
)ENGINE=InnoDB DEFAULT CHARACTER SET = utf8;

CREATE  TABLE `my_web_db`.`DOWNLOADS` (
  `download_id` INT NOT NULL ,
  `user_id` INT ,
  `download_date` DATETIME NULL ,
  `filename` VARCHAR(45) NULL ,
  `product_id` INT NOT NULL,
  PRIMARY KEY (`download_id`),
  FOREIGN KEY (user_id) REFERENCES users(user_id),
  FOREIGN KEY (product_id) REFERENCES products(product_id)
) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8;