Error Code: 1215. Can not add foreign key constraint / Error while adding foreign key

0

I'm trying to create a table called Disciplina , however I'm not getting it because of the foreign keys. I have reviewed several times and can not identify the error, if you can help me, thank you.

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;
    
asked by anonymous 21.05.2018 / 20:13

1 answer

2

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

So:

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

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

    
21.05.2018 / 20:22