无法创建表(错误号:150)InnoDB添加外键约束

Evg*_*sin 6 innodb constraints foreign-keys

真的很讨厌使用其他人的时间,但似乎问题不会消失.

我在http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/以及http://forums.mysql上考虑了所有建议..com/read.php?22,19755,19755#msg-19755但没什么.

希望有人指出一个愚蠢的错误.

这是表格:

CREATE  TABLE IF NOT EXISTS `shop`.`category` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `category_id` INT(11) NOT NULL ,
  `parent_id` INT(11) NULL DEFAULT '0' ,
  `lang_id` INT(11) NOT NULL ,
  ...other columns...
  PRIMARY KEY (`id`, `category_id`) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;



CREATE  TABLE IF NOT EXISTS `shop`.`product_category` (
  `category_id` INT(11) NOT NULL ,
  `product_id` INT(11) NOT NULL ,
  INDEX `fk_product_category_category1_zxc` (`category_id` ASC) ,
  CONSTRAINT `fk_product_category_category1_zxc`
    FOREIGN KEY (`category_id` )
    REFERENCES `shop`.`category` (`category_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;
Run Code Online (Sandbox Code Playgroud)

错误代码:1005.无法创建表'shop.product_category'(错误号:150)

Max*_*sky 9

您需要在类别表中对category_id建立索引(我看到它是主键的一部分,但由于它是索引中的第二列,因此无法使用).您在外键中引用的字段始终应编入索引.

  • @Darhazer你的回答非常有用,我试着把你的答案标记为有用,但它说我没有足够的声誉. (2认同)