Reputation: 5
CREATE TABLE Estudante (
Matrícula int,
RG int,
Nome varchar(20),
Email varchar(20),
Endereço_atual varchar(20),
Telefone_atual varchar(20),
Endereço_permanente varchar(20),
Telefone_permanente varchar(20),
Data_de_nascimento date,
Sexo varchar(1),
Série varchar(3),
Grau varchar(10),
Curso varchar(20),
PRIMARY KEY(Matrícula,RG)
);
CREATE TABLE Professor (
Matrícula int,
RG int,
CPF int,
Nome varchar(10),
Classificação varchar(3),
Endereço varchar(20),
Email varchar(10),
PRIMARY KEY(Matrícula,RG,CPF)
);
CREATE TABLE Departamento (
Nome varchar(20),
Código_departamento int,
Matrícula_prof int,
Ramal varchar(10),
Campus varchar(10),
PRIMARY KEY(Nome,Código_departamento),
CONSTRAINT FK_MatriculaProf FOREIGN KEY(Matrícula_prof) REFERENCES Professor (Matrícula)
);
CREATE TABLE Disciplina (
Código int,
Departamento_resp int,
Nome varchar(20),
Descrição varchar(20),
Carga_horária varchar(10),
Duração varchar(10),
Nível varchar(10),
PRIMARY KEY(Código),
CONSTRAINT FK_DepartamentoResp FOREIGN KEY(Departamento_resp) REFERENCES Departamento (Código_departamento)
);
CREATE TABLE Turma (
ID_Turma int,
Disciplina int,
Matricula_Instrutor int,
Período_aplicação varchar(10),
Ano int,
PRIMARY KEY(ID_Turma),
CONSTRAINT FK_Disciplina FOREIGN KEY(Disciplina) REFERENCES Disciplina (Código),
CONSTRAINT FK_MatriculaInstrutor FOREIGN KEY(Matricula_Instrutor) REFERENCES Professor (Matrícula)
);
CREATE TABLE Relatório_Notas (
Matricula_Estudante int,
Turma int,
Disciplina int,
Notas int,
PRIMARY KEY(Matricula_Estudante),
CONSTRAINT FK_MatriculaEstudante FOREIGN KEY(Matricula_Estudante) REFERENCES Estudante (Matrícula,RG),
CONSTRAINT FK_Turma FOREIGN KEY(Turma) REFERENCES Turma (ID_Turma),
CONSTRAINT FK_Disciplina FOREIGN KEY(Disciplina) REFERENCES Disciplina (Código)
);
The 3 first tables are ok, but on the "Disciplina" table I got this error: Error Code MySQL Workbench: 1215 Cannot add foreign key constraint
Upvotes: 0
Views: 1042
Reputation: 2765
You define a foreign key as
CONSTRAINT FK_DepartamentoResp FOREIGN KEY(Departamento_resp) REFERENCES Departamento (Código_departamento)
but there is no index starting with column Código_departamento on the parent table.
If you change the primary key on Departamento
from (Nome,Código_departamento)
to (Código_departamento, Nome)
(reverse column order) or add an extra index on (Código_departamento)
things should work.
In general a SHOW WARNINGS
after receiving an Cannot add foreign key constraint error reveals more detailed information on the problem.
Upvotes: 1