简体   繁体   中英

How do i solve 'Error Cannot add foreign key constraint'?

So I'm using sqlfiddle but I always get the error 'cannot add foreign key constraint'. Can somebody help me find the error? I'm sure the problem is on the first table (Professor), as if you delete both of the FK constraints, the code works perfectly.

CREATE TABLE Professor (
Inicials char(2) not null,
nom varchar(30),
DNI varchar(10),
Email varchar(30),
CONSTRAINT inicials_pk PRIMARY KEY (Inicials),
CONSTRAINT dni_professor UNIQUE (DNI),
CONSTRAINT Email_professor UNIQUE (Email)
);

INSERT INTO Professor (Inicials, nom, DNI, Email)
VALUES ('JF','Joel Ferragut','56783698V','jferragut@iesmontisa.org');
INSERT INTO Professor (Inicials, nom, DNI, Email)
VALUES ('AE','Aleix Esteve','56983698V','aesteve@iesmontisa.org');
INSERT INTO Professor (Inicials, nom, DNI, Email)
VALUES ('KC','Kevin Costes','56883698V','kevincostes@iesmontisa.org');

CREATE TABLE Grup (
Nivell varchar(10),
Curs varchar(10),
Lletra varchar(5),
Aula varchar(5),
CONSTRAINT GrupNivell_pk PRIMARY KEY (Nivell, Curs, Lletra)
);

INSERT INTO Grup (Nivell, Curs, Lletra, Aula)
VALUES ('1','2018-2019','A','24');

CREATE TABLE Docencia (
hores_totals int,
Inicials char(2) not null,
Nivell varchar(10),
Curs varchar(10),
Lletra varchar(5),
CONSTRAINT profe FOREIGN KEY (inicials)
REFERENCES Professors (inicials),
CONSTRAINT GrupNivell_pk FOREIGN KEY (Nivell, Curs, Lletra)
REFERENCES Grup (Nivell, Curs, Lletra)
);

It's a spelling mistake, your table is called Professor and your foreign key references Professors.

Try this:

CREATE TABLE Docencia (
hores_totals int,
Inicials char(2) not null,
Nivell varchar(10),
Curs varchar(10),
Lletra varchar(5),
CONSTRAINT profe FOREIGN KEY (Inicials) REFERENCES Professor (Inicials),
CONSTRAINT GrupNivell_pk FOREIGN KEY (Nivell, Curs, Lletra) REFERENCES Grup (Nivell, Curs, Lletra)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM