简体   繁体   中英

Cannot add Foreign Key constraint 1215

I got the following error: Cannot add foreign key constraint (1215) I am using MySQL workbench export tool "Forward Engineer" to obtain the code.

This is my code:

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;

I don't know what the problem is, everything seems fine to me. Any help? Created using MySQL Workbench.

Thanks

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

This foreign key is referencing a column that is not the left-most column in the season table's key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM