这个表中的外键约束有什么问题?

12 mysql sql foreign-keys

MySQL 5.1.59在这个create table中抛出一个错误:

CREATE  TABLE IF NOT EXISTS `genre` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `abv` CHAR(3) CHARACTER SET 'latin1' COLLATE 'latin1_bin' NULL DEFAULT NULL ,
  `name` VARCHAR(80) NOT NULL DEFAULT '' ,
  `parent_id` INT NULL DEFAULT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `fk_genre_genre1` (`parent_id` ASC) ,
  CONSTRAINT `fk_genre_genre1`
    FOREIGN KEY (`parent_id` )
    REFERENCES `genre` (`id` )
    ON DELETE SET NULL
    ON UPDATE CASCADE)
ENGINE = InnoDB;
Run Code Online (Sandbox Code Playgroud)

这是由MySQLWorkbench 5.2.33生成的.错误消息是:

行__的错误1005(HY000):无法创建表'mydb.genre'(错误号:150)

这个创建表出了什么问题?

手册说:

如果MySQL从CREATE TABLE语句报告错误号1005,并且错误消息引用错误150,则表创建失败,因为未正确形成外键约束.

它还说允许对同一个表的外键引用:

InnoDB支持表中的外键引用.在这些情况下,"子表记录"实际上是指同一个表中的依赖记录.

我想要的关系是一个非识别的父子,代表一个流派和子流派的层次结构.类型不必具有父类,因此parent_id可以为空.

MySQLWorkbench设置以下内容可能是相关的:

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL';
Run Code Online (Sandbox Code Playgroud)

der*_*ert 9

你的专栏idint unsigned; 你的专栏parent_idint.那些不匹配.解决的办法是改变parent_idint unsigned也.

如果你运行SHOW ENGINE InnoDB STATUS我发表评论,你会看到:

11005 17:18:38 Error in foreign key constraint of table test/genre:

    FOREIGN KEY (`parent_id` )
    REFERENCES `genre` (`id` )
    ON DELETE SET NULL
    ON UPDATE CASCADE)
ENGINE = InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Run Code Online (Sandbox Code Playgroud)

请注意"表中的列类型和引用的表不匹配"部分.


Joh*_*ica 6

这两个字段的类型不同.

CREATE  TABLE IF NOT EXISTS `genre` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,  <<-- unsigned int
  ..
  ..
  `parent_id` INT NULL DEFAULT NULL ,        <<-- signed int
  PRIMARY KEY (`id`) ,                   ***** not the same!!!!
  ....
Run Code Online (Sandbox Code Playgroud)


mad*_*ead 5

idUNSIGNEDparent_id不是未签名的.


And*_*ndy 5

字段必须是相同的类型.id是无符号的,而parent_id则不是