错误1215 MYSQL无法添加外键约束,

时间:2013-07-08 17:50:31

标签: mysql sql workbench

我有这段代码:

CREATE  TABLE IF NOT EXISTS `biblioteca`.`ejemplar` (

  `idejemplar` INT(11) NOT NULL AUTO_INCREMENT ,

  `estado` VARCHAR(45) NOT NULL ,

  `comentario` VARCHAR(45) NULL ,

  `isbn` VARCHAR(45) NOT NULL ,

  PRIMARY KEY (`idejemplar`) ,

  INDEX `fk_ejemplar_libro1_idx` (`isbn` ASC) ,

  CONSTRAINT `fk_ejemplar_libro1`

    FOREIGN KEY (`isbn` )

    REFERENCES `biblioteca`.`libro` (`isbn` )

    ON DELETE NO ACTION

    ON UPDATE NO ACTION)

ENGINE = InnoDB

DEFAULT CHARACTER SET = utf8

并且引用的表是:

CREATE  TABLE IF NOT EXISTS `biblioteca`.`libro` (
  `isbn` VARCHAR(25) NOT NULL ,
  `idcategoria` INT(11) NOT NULL ,
  `ideditorial` INT(11) NOT NULL ,
  `titulo` VARCHAR(45) NOT NULL ,
  `autor` VARCHAR(45) NOT NULL ,
  `reseña` VARCHAR(45) NULL ,
  PRIMARY KEY (`isbn`) ,
  INDEX `fk_libro2_idx` (`idcategoria` ASC) ,
  INDEX `fk_libro3_idx` (`ideditorial` ASC) ,
  CONSTRAINT `fk_libro2`
    FOREIGN KEY (`idcategoria` )
    REFERENCES `biblioteca`.`categoria` (`idcategoria` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_libro3`
    FOREIGN KEY (`ideditorial` )
    REFERENCES `biblioteca`.`editorial` (`ideditorial` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

我认为外键很好。

1 个答案:

答案 0 :(得分:2)

如果这些是没有值的新表,那么列

似乎是错误的

一个有varchar(25)另一个var_char(45)使它们相同

编辑:

CREATE  TABLE IF NOT EXISTS `biblioteca`.`libro` (
  `isbn` VARCHAR(45) NOT NULL ,
  `idcategoria` INT(11) NOT NULL ,
  `ideditorial` INT(11) NOT NULL ,
  `titulo` VARCHAR(45) NOT NULL ,
  `autor` VARCHAR(45) NOT NULL ,
  `reseña` VARCHAR(45) NULL ,
  PRIMARY KEY (`isbn`) ,
  INDEX `fk_libro2_idx` (`idcategoria` ASC) ,
  INDEX `fk_libro3_idx` (`ideditorial` ASC) )

ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;



CREATE  TABLE IF NOT EXISTS `biblioteca`.`ejemplar` (

  `idejemplar` INT(11) NOT NULL AUTO_INCREMENT ,

  `estado` VARCHAR(45) NOT NULL ,

  `comentario` VARCHAR(45) NULL ,

  `isbn` VARCHAR(45) NOT NULL ,

  PRIMARY KEY (`idejemplar`) ,

  INDEX `fk_ejemplar_libro1_idx` (`isbn` ASC) ,

  CONSTRAINT `fk_ejemplar_libro1`

    FOREIGN KEY (`isbn` )

    REFERENCES `biblioteca`.`libro` (`isbn` )

    ON DELETE NO ACTION

    ON UPDATE NO ACTION)

ENGINE = INNODB

DEFAULT CHARACTER SET = utf8;

对我来说没问题。我带走了其他2个键,虽然我没有架构