error 1215 MYSQL Cannot add foreign key constraint,
I have this code:
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
and the table that's makes reference is:
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;
and i think thats foreign keys are good.
If these are fresh tables with no values, It seems like an error with the columns
one has a varchar(25) the other a var_char(45) make them the same
edit:
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;
works no problem for me. Ive taken away the other 2 keys which i dont have schemas for though
链接地址: http://www.djcxy.com/p/86270.html