Cannot add foreign key constraint in MySQL - mysql

MySQL:
CREATE SCHEMA IF NOT EXISTS otes_db;
USE otes_db;
CREATE TABLE IF NOT EXISTS school(
school_code CHAR(3),
school_desc VARCHAR(255) NOT NULL,
school_head INT UNSIGNED NOT NULL,
PRIMARY KEY(school_code),
FOREIGN KEY(school_head) REFERENCES user(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE
)ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS user(
user_id INT UNSIGNED,
user_lname VARCHAR(255) NOT NULL,
user_fname VARCHAR(255) NOT NULL,
user_mname VARCHAR(255),
user_email VARCHAR(255) UNIQUE NOT NULL,
user_password VARCHAR(255) NOT NULL,
user_type ENUM('CEO', 'VP', 'HEAD', 'CHAIR', 'STUD') NOT NULL,
user_isActivated ENUM('Y', 'N') DEFAULT 'N',
PRIMARY KEY(user_id)
);
Based on this thread, I have checked for the following:
InnoDB Engine is set in school table
The referenced key is a primary key (user_id)
The data types are the same (INT UNSIGNED)
However, I'm still getting the error with the school_head and user_id. Anything I missed?

You need to create the user table first

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)
);

Error Code 1824 - Failed to open the referenced table

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.

MYSQL Foreign key incorrectly formed

Have an error where my first foreign key constraint is incorrectly formed. I'm waiting to hear back from my lecturer if she can spot the issue but thought I'd ask here
My SQL query is as follows
CREATE DATABASE rugby;
USE rugby;
CREATE TABLE address(
address_ID INT AUTO_INCREMENT NOT NULL,
address_name VARCHAR(50) NOT NULL,
PRIMARY KEY (address_ID)
) ENGINE=INNODB;
CREATE TABLE team(
team_ID INT AUTO_INCREMENT NOT NULL,
team_Name VARCHAR(25) NOT NULL,
team_Year INT NOT NULL,
PRIMARY KEY(team_ID)
) ENGINE=INNODB;
CREATE TABLE person(
person_ID INT AUTO_INCREMENT NOT NULL,
name VARCHAR(30) NOT NULL,
phone INT NOT NULL,
address_ID INT NOT NULL,
email VARCHAR(50),
photo BLOB,
PRIMARY KEY(person_ID),
FOREIGN KEY(address_ID) REFERENCES address(address_ID) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=INNODB;
I have followed how we were taught but can't spot the issue.
Any help appreciated
In table person you have defined address_ID as NOT NULL, but
when you define the FOREIGN KEY you set:
ON DELETE SET NULL
which contradicts the NOT NULL definition.

Cannot delete or update a parent row: a foreign key constraint fails Error

i am trying to delete the table appusers, with the following command:
drop table appusers;
and i get the following error:
Cannot delete or update a parent row: a foreign key constraint fails
this is the scheme for my tables.
CREATE TABLE appUsers (
uid INT PRIMARY KEY AUTO_INCREMENT,
fullName VARCHAR(80) NOT NULL,
email VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
Gender VARCHAR(7) NOT NULL, /*["Male", "Female"]*/
Country VARCHAR(150) NOT NULL,
Bdate date NOT NULL,
Status VARCHAR(25) NOT NULL, /*["Single", "In Relationship", "Merried", "Divorced", "Widow"]*/ /*check married!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
Religion VARCHAR(25) NOT NULL, /*["Jewish", "Christian", "Muslim", "Atheist", "Other"]*/
ReligionStrength INT(1) NOT NULL, /*0-5*/
PoliticalView VARCHAR(25) NOT NULL, /*["Left Wing","Center","Right Wing"]*/
Occupation VARCHAR(25) NOT NULL, /*["Unemployed","White Collar","Blue Collar","Student", "Independent"]*/
Volunteering VARCHAR(25) NOT NULL, /*["Yes", "No"]*/
Donating VARCHAR(25) NOT NULL, /*["Yes", "No"]*/
Economy VARCHAR(25) NOT NULL, /*["Poor","Middle Class","Rich"]*/
EducationalYears INT(2) NOT NULL
);
and I have the following table
CREATE TABLE Accelerometer(
id INT PRIMARY KEY AUTO_INCREMENT,
uid INT NOT NULL,
sampleTime timestamp(2) NOT NULL,
data VARCHAR(100) NOT NULL,
FOREIGN KEY (uid) REFERENCES appUsers(uid) ON DELETE CASCADE
);
as far as I know, if I delete the table appusers, the Accelerometer table should be deleted too,
what i am missing here?
ON DELETE CASCADEonly apply to data, not metadata.
=>
Alter TABLE Accelerometer drop FOREIGN KEY (uid);
Then only
drop table appusers;
I realise this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
The following might work nicely for you:
ALTER TABLE 'Accelerometer'
DROP FOREIGN KEY 'uid_fk';
ALTER TABLE 'Accelerometer'
ADD CONSTRAINT 'uid_fk' FOREIGN KEY ('uid') REFERENCES 'appUsers' ('uid') ON
UPDATE CASCADE ON DELETE SET NULL;`
Personally I would recommend using both ON UPDATE CASCADE as well as ON DELETE SET NULL to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.

Child Table variable allows NULL but the ON DELETE SET NULL still isn't working?

When I try to set the Foreign Key to ON DELETE SET NULL it won't create the table (ERROR 1005 (HY000):). If I change it to ON DELETE CASCADE it works. So I'm fairly certain that's the issue.
I have a table called ORDERHASSHIPPINGADDRESS that maintains the many-to-many relationship between CUSTORDER table and ADDRESS table. When a customer deletes an order this can cascade through and delete the record in ORDERHASSHIPINGADDRESS, but when an address is deleted it shouldn't delete the record in ORDERHASSHIPINGADDRESS - then it should just be set to NULL until it can be updated to something else. So I made sure the child table variable "addrID" allows NULL. I made sure InnoDB allows this. What else am I missing? Thank you in advance for your help.
CREATE TABLE USER (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
userName VARCHAR(20) NOT NULL UNIQUE,
email VARCHAR(25) NOT NULL UNIQUE,
firstName VARCHAR(15) NOT NULL,
lastName VARCHAR(20) NOT NULL,
salt CHAR(10) NOT NULL,
HASH CHAR(40)
)ENGINE=InnoDB;
CREATE TABLE ADDRESS (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
addName VARCHAR(25) NOT NULL UNIQUE,
streetAddress VARCHAR(50) NOT NULL,
city VARCHAR (25) NOT NULL,
state VARCHAR(2) NOT NULL,
zip CHAR(5) NOT NULL,
phone VARCHAR(10),
addrUserID INT UNSIGNED NOT NULL,
FOREIGN KEY (addrUserID) REFERENCES USER(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
CREATE TABLE FUNDS (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
cardNumber VARCHAR(19) NOT NULL UNIQUE,
sudoName VARCHAR(25),
expDate DATE NOT NULL,
securityCode VARCHAR(5) NOT NULL UNIQUE,
billAddrID INT UNSIGNED,
FOREIGN KEY (billAddrID) REFERENCES ADDRESS(id) ON DELETE SET NULL ON UPDATE CASCADE
)ENGINE=InnoDB;
CREATE TABLE CUSTORDER (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
invoiceDate DATE NOT NULL,
orderUserID INT UNSIGNED,
orderFundsID INT UNSIGNED,
FOREIGN KEY (orderUserID) REFERENCES USER(id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (orderFundsID) REFERENCES FUNDS(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
CREATE TABLE ORDERHASSHIPPINGADDRESS (
orderID INT UNSIGNED NOT NULL,
addrID INT UNSIGNED,
PRIMARY KEY (orderID, addrID),
FOREIGN KEY (orderID) REFERENCES CUSTORDER(id) on DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (addrID) REFERENCES ADDRESS(id) on DELETE SET NULL on UPDATE CASCADE
)ENGINE=InnoDB;
MySQL won't allow the SET NULL because I set the variable addrID as one of the PRIMARY KEYS so it cannot be null.