Error Code 1824 - Failed to open the referenced table - mysql

I'm trying to create my DB project on MySQL, and when I tried to add foreign keys, it show the error code 1824 on all of the tables I'm trying to create. My code is this:
create table cliente (
id_cliente varchar(20) not null primary key,
nome varchar(50) unique not null,
endereco varchar(70) not null,
celular varchar(15) not null,
id_cartao_cliente int not null,
cod_encomenda_cliente int not null,
constraint fk_cartao foreign key (id_cartao_cliente) references cartao_credito(id_cartao),
constraint fk_encomenda foreign key (cod_encomenda_cliente) references encomenda(cod_encomenda)
) engine = innodb;
create table cartao_credito (
id_cartao int not null primary key,
num_cartao varchar(20) not null,
nome_cartao varchar(30) not null,
mes_validade varchar(2) not null,
ano_validade year,
id_cliente_cartao varchar(20) not null,
constraint fk_cliente foreign key (id_cliente_cartao) references cliente(id_cliente)
) engine = innodb;
create table Encomenda (
cod_encomenda int not null primary key,
tipo varchar(15) not null,
valor_encomenda varchar(10) not null,
local_destino varchar(20) not null,
id_destinatario_encomenda varchar(20) not null,
constraint fk_destinatario foreign key (id_destinatario_encomenda) references destinatario(id_destinatario)
) engine = innodb;
create table movimentacao (
id varchar(50) not null primary key,
local_movimentacao varchar(50) not null,
descricao varchar(30) not null,
data_movimentacao date not null,
hora_movimentacao time not null,
cod_encomenda_movimentacao int not null,
id_entregador_movimentacao varchar(20) not null,
foreign key (cod_encomenda_movimentacao) references encomenda(cod_encomenda),
foreign key (id_entregador_movimentacao) references entregador(id_entregador)
) engine = innodb;
create table entregador (
id_entregador varchar(20) not null primary key,
nome varchar(50) unique not null,
placa_veiculo varchar(10) not null,
tipo_veiculo varchar(15) not null,
cod_encomenda_entregador varchar(50) not null,
id_destinatario_entregador varchar(20) not null,
foreign key (cod_encomenda_entregador) references encomenda(cod_encomenda),
foreign key (id_destinatario_entregador) references destinatario(id_destinatario)
) engine = innodb;
create table destinatario (
id_destinatario varchar(20) not null primary key,
nome varchar(50) not null unique not null,
endereco varchar(70) not null,
celular varchar(15) not null,
cod_encomenda_destinatario int not null,
foreign key (cod_encomenda_destinatario) references encomenda(cod_encomenda)
) engine = innodb;
I need help with this code please.
P.S.: all of the columns are written in Portuguese

MySQL error code 1824 is "Failure to open referenced table."
I believe you are running into trouble because of the order you are creating in. I see that "Encomenda" does not have a foreign key, and may be a good place to start your creation.

Your design is wrong. Because when an entity in cliente refer to cartao_credito it means there is a (1 to N) relation between these two table. So no need to refer cartao_credito to cliente again. If you need an N to N relationship use a bridge (a new table) between them and use two 1 to N relationship.
In your design all tables refer to each other mutually. For example in two first table you need just one foreign key to join these two tables not two foreign key.

Related

I am getting an Error 1822 failed when trying to create MySQL tables

When I try and run this query, I get an error:
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint.
However, based on other posts, I have ensured the data types were matching. Can someone please help me out? The issue is with the last table.
CREATE TABLE Client
(
client_id int NOT NULL,
client_name varchar(50) NOT NULL,
client_address varchar(50) NOT NULL,
client_city varchar(10) NOT NULL,
client_prov varchar(2) NOT NULL,
client_postal varchar(6) NOT NULL,
PRIMARY KEY (client_id),
UNIQUE (client_name)
);
CREATE TABLE Programmer
(
prog_id decimal(5,0),
prog_name varchar(30) NOT NULL,
prog_office char(5) NOT NULL,
prog_phone char(10) NOT NULL,
PRIMARY KEY (prog_id)
);
CREATE TABLE Project
(
project_id decimal(6,1),
project_name varchar(40) NOT NULL,
complete_date date ,
total_cost decimal(7,2) NOT NULL,
client_id int NOT NULL,
UNIQUE (project_name),
FOREIGN KEY (client_id) REFERENCES Client (client_id),
CHECK (complete_date > "2020-01-01"),
CHECK(total_cost > 0)
);
CREATE TABLE Project_mm_Programmer
(
prog_id decimal(5,0),
project_id decimal(6,1),
hours_worked decimal(3,1), -- NOT NULL,
FOREIGN KEY (prog_id) REFERENCES Programmer (prog_id) ,
FOREIGN KEY (project_id) REFERENCES Project (project_id),
CHECK(hours_worked > 0)
);
The Issue is on the creation of the last table. It references a PK for the bridging table. The foreign key uses Project ID PK but..
Your table Project doesn't have a primary key like the Programmer and Client Tables do
CREATE TABLE Client (
client_id int NOT NULL,
client_name varchar(50) NOT NULL,
client_address varchar(50) NOT NULL,
client_city varchar(10) NOT NULL,
client_prov varchar(2) NOT NULL,
client_postal varchar(6) NOT NULL,
primary key (client_id),
unique (client_name)
);
CREATE TABLE Programmer (
prog_id decimal(5,0),
prog_name varchar(30) NOT NULL,
prog_office char(5) NOT NULL,
prog_phone char(10) NOT NULL,
primary key (prog_id)
);
CREATE TABLE Project (
project_id decimal(6,1),
project_name varchar(40) NOT NULL,
complete_date datetime,
total_cost decimal(7,2) NOT NULL,
client_id int NOT NULL,
unique (project_name),
FOREIGN KEY (client_id) REFERENCES Client (client_id),
CHECK (complete_date > '2020-01-01'), -- may have to change back to double ticks
CHECK(total_cost>0),
primary key (project_id) -- add this line for sure
);
CREATE TABLE Project_mm_Programmer (
prog_id decimal(5,0),
project_id decimal(6,1),
hours_worked decimal(3,1), -- NOT NULL,
FOREIGN KEY (prog_id) REFERENCES Programmer (prog_id) ,
FOREIGN KEY (project_id) REFERENCES Project (project_id),
CHECK(hours_worked>0)
);

MySQL ERROR 1215 (HY000): Cannot add foreign key constraint when I'm trying to create a table

I tried looking up the reasons why it's failing but I can't find the different data types issues mentioned in the solutions in my tables.
I'm getting the error when I'm trying to run the following:
comments (id int NOT NULL AUTO_INCREMENT,
user_id varchar(10) NOT NULL,
blog_id int NOT NULL,
comment varchar(150) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(user_id) REFERENCES user_details(id),
FOREIGN KEY(blog_id) REFERENCES blog(id));
existing data bases for primary keys:
user_details (id varchar(10) NOT NULL ,
name varchar(70) NOT NULL,
email varchar(40) NOT NULL,
salt varchar(40) NOT NULL,
masked_password varchar(40) NOT NULL,
is_active varchar(10) DEFAULT 'False');
blog (id int NOT NULL AUTO_INCREMENT,
category_id int NOT NULL,
title varchar(240) NOT NULL,
body longtext NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY(category_id) REFERENCES blog_catagories(id));
Let me know where I'm going wrong

MySQL Error 1215 creating foreign key

My question is about MySQL, I keep getting an error (Error 1215: Cannot add Foreign key Constraint) while trying to forward engineer a schema to a db server, I've got two parent tables:
CREATE TABLE IF NOT EXISTS alunos (
idAluno INT NOT NULL AUTO_INCREMENT,
NomeAluno VARCHAR(100) NOT NULL,
nifAluno VARCHAR(15) NOT NULL,
moradaAluno VARCHAR(255) NOT NULL,
telefoneAluno VARCHAR(9) NOT NULL,
emailAluno VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
PRIMARY KEY(idAluno, nifAluno)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS cursos (
idCurso INT NOT NULL AUTO_INCREMENT,
nomeCurso VARCHAR(50) NOT NULL,
horas INT NOT NULL,
PRIMARY KEY(idCurso, nomeCurso)
) ENGINE=INNODB;
And this is my child table:
CREATE TABLE IF NOT EXISTS inscritos (
id INT NOT NULL AUTO_INCREMENT,
Nome VARCHAR(100) NOT NULL,
Morada VARCHAR(255) NOT NULL,
Naturalidade VARCHAR(45) NOT NULL,
NIF VARCHAR(15) NOT NULL,
email VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
Telefone VARCHAR(9) NOT NULL,
Curso VARCHAR(50) NOT NULL,
Horas INT NOT NULL,
Inicio DATE NOT NULL,
Validade DATE NOT NULL,
Atividade VARCHAR(45) NOT NULL,
PRIMARY KEY(id),
INDEX(NIF),
INDEX(Curso),
FOREIGN KEY(NIF)
REFERENCES alunos(nifAluno)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY(Curso)
REFERENCES cursos(nomeCurso)
ON UPDATE RESTRICT ON DELETE RESTRICT
) ENGINE=INNODB;
I've looked through the code over and over and I can't seem to find the error when assigning the foreign keys.
Thanks in advance.
Because, NIF and Curso aren't primary/unique key in inscritos table. Creating index doesn't mean you are creating key on same column. So, just for your information. The referenced columns in the Parent table must be the left-most columns of a key. Best if the key is PRIMARY KEY or UNIQUE KEY.
As #Bill commented, he has an answer where he has prepared a checklist, you may refer to make sure, you won't get any other error.

MySQL Workbench won't allow me to create foreign keys

I'm trying to create a few tables and one of them has should have foreign keys referencing the other tables, but MySQL Workbench keeps giving me "Error Code: 1215. Cannot add foreign key constraint". This happens if I try to create them during the table creation and if I just create the table and then try to add FK through ALTER. I just can't figure out the problem. I've tried both with and without ENGINE = InnoDB that I saw some people suggest on the web. And yes, tables kommune and person has been created.
CREATE TABLE kommune (
Kommunenr varchar(4) NOT NULL,
Kommunenavn varchar(45) NOT NULL,
PRIMARY KEY (Kommunenr));
CREATE TABLE person (
PersonID varchar(4) NOT NULL,
Fornavn varchar(45) NOT NULL,
Etternavn varchar(45) NOT NULL,
Postnr varchar(4) NOT NULL,
Poststed varchar(45) NOT NULL,
PRIMARY KEY (PersonID));
CREATE TABLE oppdrag (
Oppdragsnr varchar(5) NOT NULL,
Eiendomnr varchar(4) NOT NULL,
Gateadresse varchar(45) NOT NULL,
Postnr varchar(4) NOT NULL,
Poststed varchar(45) NOT NULL,
Kommunenr varchar(4) NOT NULL,
Prisantydning varchar(10) NOT NULL,
Solgt boolean NOT NULL,
PRIMARY KEY (Oppdragsnr),
FOREIGN KEY (Postnr) REFERENCES person(Postnr),
FOREIGN KEY (Poststed) REFERENCES person(Poststed),
FOREIGN KEY (Kommunenr) REFERENCES kommune(Kommunenr));
Check the following lines:
FOREIGN KEY (Postnr) REFERENCES person(Postnr),
FOREIGN KEY (Poststed) REFERENCES person(Poststed),
but in your table structure:
CREATE TABLE person (
PersonID varchar(4) NOT NULL,
Fornavn varchar(45) NOT NULL,
Etternavn varchar(45) NOT NULL,
Postnr varchar(4) NOT NULL,
Poststed varchar(45) NOT NULL,
PRIMARY KEY (PersonID));
Postnr, Poststed are neither unique or not primary key. To make foreign key, the referring column in the base table must be an indexed column

Mysql foreign key constraint is incorrectly formed?

I am receiving an error when attempting to create some tables in mysql with the foreign key
CREATE TABLE session (
code CHAR(2) NOT NULL,
date DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (date),
CONSTRAINT session_fk FOREIGN KEY (code)
REFERENCES module(code));
CREATE TABLE module (
code CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (code));
Here are the two tables I am trying to create, the syntax I've used matches w3 schools and both data types are the same so I cannot see how this is incorrect, any help would be appreciated thanks :)
You're trying to create a foreign key on table before creating the referencing table.
Interchanging the order of query will work :
CREATE TABLE module (
`code` CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (`code`));
CREATE TABLE `session` (
`code` CHAR(2) NOT NULL,
`date` DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (`date`),
CONSTRAINT session_fk FOREIGN KEY (`code`)
REFERENCES module(`code`));
Try this
CREATE TABLE module (
code CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (code));
CREATE TABLE session (
code CHAR(2) NOT NULL,
date DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (date),
CONSTRAINT session_fk FOREIGN KEY (code)
REFERENCES module(code));