Error Code: 1215. Cannot add Foreign key Constraint/ Error to add foreign key

Asked

Viewed 164 times

0

I’m trying to create a table called Disciplina, however I am not getting on account of foreign keys. I’ve checked it over and over and I can’t identify the mistake, if you can help me, I’d appreciate it.

CREATE TABLE `Curso` (
  `idCurso` INT NOT NULL auto_increment,
  `nomeCurso` VARCHAR(45),
  `tipoCurso` VARCHAR(45),
  PRIMARY KEY (`idCurso`))
ENGINE = InnoDB;

CREATE TABLE `Matriz` (
  `Curso_idCurso` INT NOT NULL,
  `anoInicio` INT NOT NULL,
  `anoFim` INT NOT NULL,
  `status` TINYINT NOT NULL,
  `tituloMatriz` VARCHAR(45) NOT NULL,
  `Disciplina_codDisciplina` VARCHAR(15) NOT NULL,
  PRIMARY KEY (`Curso_idCurso`, `anoInicio`),
  INDEX `fk_Matriz_Curso1_idx` (`Curso_idCurso` ASC),
  CONSTRAINT `fk_Matriz_Curso1`
    FOREIGN KEY (`Curso_idCurso`)
  REFERENCES `Curso` (`idCurso`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE TABLE `Disciplina` (
  `codDisciplina` VARCHAR(15) NOT NULL,
  `nome` VARCHAR(45) NOT NULL,
  `corrente` TINYINT NOT NULL,
  `Matriz_anoInicio` INT NOT NULL,
  `Matriz_idCurso` INT NOT NULL,
  PRIMARY KEY (`codDisciplina`, `Matriz_anoInicio`,`Matriz_idCurso`),
  FOREIGN KEY (`Matriz_idCurso`) 
      REFERENCES `Matriz` (`Curso_idCurso`),
  FOREIGN KEY (`Matriz_anoInicio`)
      REFERENCES `Matriz` (`anoInicio`))    
ENGINE = InnoDB;

1 answer

3


On the table Matriz you are declaring as primary key the composition of Curso_idCurso and anoInicio. Already on the table Disciplina you are trying to create a reference from only Matriz_idCurso. The reference statement should include all key fields of the parent table.

Thus:

...
FOREIGN KEY (`Matriz_idCurso`,`Matriz_anoInicio`) 
      REFERENCES `Matriz` (`Curso_idCurso`, `anoInicio`)
...

Particularly I abandoned the use of composite keys years ago. In practice its use only generates more work, especially when using a relational object mapping.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.