I was creating a database for a school project and I have this issue while doing it.
I'm using MySQL workbench 8.0.29
This is the database structure i'm following
Database_design
And the SQL:
CREATE DATABASE AEROPORTS;
USE AEROPORTS;
CREATE TABLE PILOTS (
IDENTIFICADOR INT,
NOM VARCHAR(15),
COGNOMS VARCHAR(30),
HORES_VOL INT,
PRIMARY KEY (IDENTIFICADOR)
)engine=innodb;
CREATE TABLE AEROPORTS (
NOM VARCHAR(20),
CIUTAT VARCHAR(20),
PRIMARY KEY (NOM)
)engine=innodb;
CREATE TABLE COMPANYIES (
IDENTIFICADOR INT,
NOM VARCHAR(20),
NACIONALITAT VARCHAR(20),
LOGO varbinary(50),
PRIMARY KEY (IDENTIFICADOR)
)engine=innodb;
CREATE TABLE VOLS (
COMPANYIA INT,
NUMERO_VOL INT,
SORTIDA DATETIME,
ARRIBADA DATETIME,
ORIGEN VARCHAR(20),
DESTI VARCHAR(20),
PRIMARY KEY (COMPANYIA, NUMERO_VOL),
FOREIGN KEY (COMPANYIA) REFERENCES COMPANYIES (IDENTIFICADOR),
FOREIGN KEY (DESTI) REFERENCES AEROPORTS (NOM)
)engine=innodb;
CREATE TABLE PASSATGERS (
COMPANYIA INT,
VOL INT,
NOM VARCHAR(15),
COGNOMS VARCHAR(30),
CLASSE VARCHAR(15),
PRIMARY KEY (COMPANYIA, VOL, NOM, COGNOMS),
FOREIGN KEY (COMPANYIA) REFERENCES VOLS (COMPANYIA),
FOREIGN KEY (VOL) REFERENCES VOLS (NUMERO_VOL)
)engine=innodb;
CREATE TABLE PILOTAR (
COMPANYIA INT,
VOL INT,
PILOT INT,
PRIMARY KEY (COMPANYIA, VOL, PILOT),
FOREIGN KEY (COMPANYIA) REFERENCES VOLS (COMPANYIA),
FOREIGN KEY (PILOT) REFERENCES PILOTS (IDENTIFICADOR)
)engine=innodb;
CREATE TABLE AVIONS (
NUMERO_AVIO INT,
HORES_VOLS DATETIME,
PLACES_PRIMERA INT,
PLACES_TURISTA INT,
COMPANYIA INT,
PRIMARY KEY (NUMERO_AVIO),
FOREIGN KEY (COMPANYIA) REFERENCES COMPANYIES (IDENTIFICADOR)
)engine=innodb;
I'm having some problems linking "COMPANYIES" from "PASSATGERS" table
This is the error that the application throws me
error_code
To reference a multi-column primary key in VOLS, make the foreign key have the same number of columns.
WRONG:
FOREIGN KEY (COMPANYIA) REFERENCES VOLS (COMPANYIA),
FOREIGN KEY (VOL) REFERENCES VOLS (NUMERO_VOL)
RIGHT:
FOREIGN KEY (COMPANYIA, VOL) REFERENCES VOLS (COMPANYIA, NUMERO_VOL)
Related
I am having a hard time understanding why my code is giving me cannot add foreign key constraint error. I just started coding in MySQL so I am sorry for anything dumb.
drop table if exists COURSE_INSTRUCTORJG;
drop table if exists CLASSJG;
drop table if exists COURSEJG;
drop table if exists INSTRUCTORJG;
create table INSTRUCTORJG(
InstructorID int,
DepartHead int,
primary key(InstructorID)
);
create table COURSEJG(
CourseNo char(10),
ComputerNeeded smallint,
primary key(CourseNo)
);
create table CLASSJG(
Building CHAR(20),
RoomNum smallint,
Maxcap int,
primary key(Building, RoomNum)
);
create table COURSE_INSTRUCTORJG (
COURSEJG_CourseNo CHAR(10),
INSTRUCTORJG_InstructorID INT,
Semester CHAR(20),
Section INT,
CLASSJG_Building char(20),
CLASSJG_RoomNum smallint,
primary key(COURSEJG_CourseNo, INSTRUCTORJG_InstructorID, Semester, Section),
foreign key (COURSEJG_CourseNo) references COURSEJG(CourseNo),
foreign key (INSTRUCTORJG_InstructorID) references INSTRUCTORJG(InstructorID),
foreign key (CLASSJG_Building) references CLASSJG(Building),
foreign key (CLASSJG_RoomNum) references CLASSJG(RoomNum)
);
My error is coming from the line: foreign key (CLASSJG_RoomNum) references CLASSJG(RoomNum).
You can reference primary key, keys or unique comnstrqaint, but in table CLASSJG you have a double primary key, so reference both columns or define another key
create table CLASSJG(
Building CHAR(20),
RoomNum smallint,
Maxcap int,
primary key(Building, RoomNum),
KEY(RoomNum)
);
see sample fiddle
Hope somone can help me.
Session Table is here:
CREATE TABLE User (
UID int,
Name varchar(40),
Vorname varchar(15),
Titel varchar(40),
Geschlecht int,
EMailAdr varchar(40),
SHID int,
Guthaben int ,
PRIMARY KEY (UID),
FOREIGN KEY (SHID) REFERENCES Schule(SHID),
UNIQUE (EMailAdr)
);
CREATE TABLE Schule (
SHID int,
Name varchar(40),
Adr varchar(80),
PRIMARY KEY (SHID),
UNIQUE (Adr),
UNIQUE (Name)
);
CREATE TABLE Lokal (
LID int,
Name varchar(40),
Adr varchar(40),
KontoNr varchar(40),
PRIMAYR KEY (LID),
UNIQUE (Adr),
UNIQUE (Name)
);
CREATE TABLE Zahlungsarten (
ZID int,
Bezeichnung varchar(40),
PRIMARY KEY (ZID)
);
CREATE TABLE BestellteArtikel (
ArID int,
BID int,
Anzahl int,
PRIMARY KEY (ArID,BID)
);
CREATE TABLE Status (
SID int,
Bezeichnung varchar(40),
PRIMARY KEY (SID)
);
CREATE TABLE Artikel (
ArID int,
Bezeichnuhg varchar(40),
Beschreibung varchar(120),
Preis int,
LID int,
Liefervolumen int,
PRIMARY KEY (ArID),
UNIQUE (Bezeichnung)
);
CREATE TABLE Bestellungen (
BID int,
UID int,
Datum Date,
ZID int,
SID int,
SHID int,
LID int,
PRIMARY KEY (BID),
FOREIGN KEY (UID) REFERENCES User(UID),
FOREIGN KEY (ZID) REFERENCES Zahkungsarten(ZID),
FOREIGN KEY (SID) REFERENCES Status(SID),
FOREIGN KEY (SHID) REFERENCES Schule(SHID),
FOERIGN KEY (LID) REFERENCES Lokal(LID)
);
There are several problems.
In table User:
You're referencing the table Schule before you have created the latter table. The table must exist before you can declare a foreign key that references it. So this works if you create Schule before you create User (I tested it, and it works).
In table Lokal:
PRIMAYR KEY (LID),
You mistyped PRIMARY.
In table Artikel:
Bezeichnuhg varchar(40),
I think you mistyped Bezeichnung.
In table Bestellungen:
FOERIGN KEY (LID) REFERENCES Lokal(LID)
You mistyped FOREIGN.
With all due respect, you should have been able to correct these mistakes yourself without posting a question to Stack Overflow. Most of them are obvious spelling errors.
CREATE TABLE Departament
(d_nume varchar(30), d_nr int, manager varchar(30), PRIMARY KEY(d_nr),
FOREIGN KEY (manager) REFERENCES Angajat(nume));
CREATE TABLE Angajat
(nume varchar(30), prenume varchar(30), cnp char(13), d_nr int, PRIMARY KEY(cnp),
FOREIGN KEY(d_nr) REFERENCES Departament(d_nr));
"Cannot add foreign key constraint"
I use this editor online http://sqlfiddle.com/
When two tables reference each other, you can use alter table:
CREATE TABLE Departament (
d_nr int,
d_nume varchar(30),
manager char(13),
PRIMARY KEY (d_nr)
);
CREATE TABLE Angajat (
cnp char(13),
nume varchar(30),
prenume varchar(30),
d_nr int,
PRIMARY KEY(cnp),
FOREIGN KEY(d_nr) REFERENCES Departament(d_nr)
);
ALTER TABLE Departament ADD CONSTRAINT FOREIGN KEY (manager) REFERENCES Angajat(cnp);
Foreign key references should also be to the primary key, which I normally make the first column in a table. Here is a SQL Fiddle.
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
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.
I am trying to create 5 tables (should not be too hard), but I am having issues assigning the foreign keys. PhpMyAdmin gives me this error:
Can't create table 'databasexx.gave' (errno: 150)
Basically all the tables with no foreign keys are created.
DROP TABLE IF EXISTS oppbygging;
CREATE TABLE oppbygging (
gnr INT,
dnr INT,
ant INT,
CONSTRAINT dnr_grn_pk PRIMARY KEY (gnr, dnr)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS onske;
CREATE TABLE onske (
onr INT,
pnr INT,
gnr INT,
prioriet INT,
ferdig INT,
CONSTRAINT pnr_gnr_pk PRIMARY KEY (pnr, gnr)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS person;
CREATE TABLE person (
pnr INT,
fornavn VARCHAR(64),
etternavn VARCHAR(64),
fdato DATE,
CONSTRAINT pnr_pk PRIMARY KEY (pnr),
CONSTRAINT person_pnr_fk FOREIGN KEY (pnr) REFERENCES onske(pnr)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS gave;
CREATE TABLE gave
(
gnr int,
navn varchar (255) UNIQUE,
prod_tid int NOT NULL,
CONSTRAINT gnr_pk PRIMARY KEY (gnr),
CONSTRAINT gave_gnr_fk FOREIGN KEY (gnr) REFERENCES oppbygging(gnr),
CONSTRAINT gave_gnr_fk FOREIGN KEY (gnr) REFERENCES onske(gnr)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS del;
CREATE TABLE del (
dnr INT,
navn VARCHAR(64),
lager_ant INT NOT NULL,
CONSTRAINT dnr_pk PRIMARY KEY (dnr),
CONSTRAINT del_dnr_fk FOREIGN KEY (dnr) REFERENCES oppbygging(dnr)
) ENGINE=InnoDB;
I am sure that I am making some sort of obvious mistake, but I just cannot figure it out. Any help would be very much appreciated.
Here is the relationship view, ignore the Eiendom table:
TO CREATE ANOTHER TABLE WITH A FOREIGN KEY, THE FOREIGN KEY
SPECIFIED MUST BE THE PRIMARY KEY OF AT LEAST ONE TABLE
THAT HAS ALREADY BEEN CREATED,E.G.
CREATE TABLE 1 WITH THE PRIMARY KEY:
CREATE TABLE PERSONS(
PERSON_ID INT(10),
FNAME VARCHAR(20)NOT NULL,
LNAME VARCHAR(20),
DOB DATETIME,
AMOUNTPAID DECIMAL(15,2),
PRIMARY KEY(PERSON_ID)
);
THEN CREATE TABLE 2 WITH THE FOREIGN KEY:
CREATE TABLE COMMENTS(
COMMENTID INT AUTO_INCREMENT,
COMMENTS VARCHAR(500),
PERSON_ID INT(10),
PRIMARY KEY(COMMENTID),
FOREIGN KEY (PERSON_ID) REFERENCES PERSONS(PERSON_ID)
);