无法添加外键约束1215

时间:2014-10-30 22:25:53

标签: mysql sql database foreign-keys erd

我收到以下错误:无法添加外键约束(1215) 我正在使用MySQL工作台导出工具" Forward Engineer"获得代码。

这是我的代码:

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,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;

CREATE TABLE IF NOT EXISTS `mydb`.`serie` (
  `serieid` INT NOT NULL,
  `name` VARCHAR(30) NOT NULL,
  PRIMARY KEY (`serieid`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `mydb`.`season` (
  `serieid` INT NOT NULL,
  `seasonid` INT NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `description` TEXT NULL,
  PRIMARY KEY (`serieid`, `seasonid`),
  CONSTRAINT `fk_season_serie`
    FOREIGN KEY (`serieid`)
    REFERENCES `mydb`.`serie` (`serieid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `mydb`.`episode` (
  `serieid` INT NOT NULL,
  `seasonid` INT NOT NULL,
  `episodeid` INT NOT NULL,
  `title` VARCHAR(100) NOT NULL,
  `description` TEXT NULL,
  PRIMARY KEY (`serieid`, `seasonid`, `episodeid`),
  INDEX `fk_episode_season1_idx` (`seasonid` ASC),
  CONSTRAINT `fk_episode_serie1`
    FOREIGN KEY (`serieid`)
    REFERENCES `mydb`.`serie` (`serieid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_episode_season1`
    FOREIGN KEY (`seasonid`)
    REFERENCES `mydb`.`season` (`seasonid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

我不知道问题是什么,一切似乎都很好。有帮助吗? 使用MySQL Workbench创建。

由于

1 个答案:

答案 0 :(得分:1)

CREATE TABLE IF NOT EXISTS `mydb`.`episode` (
. . .
FOREIGN KEY (`seasonid`)
REFERENCES `mydb`.`season` (`seasonid`)

此外键引用的列不是season表键中最左侧的列。