MySQL Error 1215 creating foreign key - mysql

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.

Related

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.

Error number: 3780 Referencing column '%s' and referenced column '%s' in foreign key constraint '%s' are incompatible

DROP DATABASE IF EXISTS ProviderPatients;
CREATE DATABASE ProviderPatients;
USE ProviderPatients;
CREATE TABLE IF NOT EXISTS Date_Dim
(
Date_ID integer not null,
Date_ date,
Full_Date_Des varchar(25) not null,
Day_Of_Week int(11) not null,
Calender_Year int(11) not null,
Weekday_Indicator int(11) not null,
PRIMARY KEY (Date_ID)
);
CREATE TABLE IF NOT EXISTS Insurer_DIM
(
Insurer_ID int(11) not null,
Insurer_Name varchar(25) not null,
Line_Of_Buissness varchar(25) not null,
PRIMARY KEY (Insurer_ID)
);
CREATE TABLE IF NOT EXISTS Member_DIM
(
Member_ID int(11) not null,
Member_Name varchar(25) not null,
Age int(11) not null,
Ethnicity varchar(25) not null,
Health_Condition varchar(25) not null,
PRIMARY KEY (Member_ID)
);
CREATE TABLE IF NOT EXISTS Geography_Dim
(
Geography_ID varchar(25) not null,
Country varchar(25) not null,
State varchar(10) not null,
State_Code int(11) not null,
County_Code int(11) not null,
PRIMARY KEY (Geography_ID)
);
CREATE TABLE Provider_Dim
(
Provider_ID int(11) not null,
Provider_Name VARCHAR(45) NOT NULL,
Gender Varchar(25) Not Null,
NPI Varchar(25) Not Null,
Credential Varchar(25) Not Null,
PRIMARY KEY(Provider_ID)
);
CREATE TABLE Eval_Fact_Table
(
Date_ID int(11) not null,
Member_ID int(11) not null,
Provider_ID int(11) not null,
Insurer_ID int(11) not null,
Geography_ID int(11) not null,
Num_Visits int(11) not null,
Eval_Costint int(11) not null,
Eval_Start date not null,
Eval_End date not null,
FOREIGN KEY (Date_ID)
REFERENCES Date_Dim (Date_Id) ON DELETE RESTRICT,
FOREIGN KEY (Member_ID)
REFERENCES Member_Dim (Member_ID) ON DELETE RESTRICT,
FOREIGN KEY (Geography_ID)
REFERENCES Geography_Dim (Geography_ID) ON DELETE RESTRICT,
FOREIGN KEY (Provider_ID)
REFERENCES Proveider_Dim (Provider_ID) ON DELETE RESTRICT,
FOREIGN KEY (Insurer_ID)
REFERENCES Insurer_Dim (Insurer_ID) ON DELETE RESTRICT
);
Error number: 3780; Symbol: ER_FK_INCOMPATIBLE_COLUMNS; SQLSTATE: HY000
Message:Error Code: 3780. Referencing column 'Geography_ID' and referenced column 'Geography_ID' in foreign key constraint 'eval_fact_table_ibfk_3' are incompatible.
Error Referencing column 'Geography_ID' and referenced column 'Geography_ID' in foreign key constraint 'eval_fact_table_ibfk_3' are incompatible.
is quite clear, columns are incompatible:
CREATE TABLE IF NOT EXISTS Geography_Dim (
Geography_ID varchar(25) not null,
CREATE TABLE Eval_Fact_Table(
... truncated
Geography_ID int(11) not null,
Make them of same type or remove foreign key constraint.
You can read more about foreign key constraints in documentation, most interesting part is
Corresponding columns in the foreign key and the referenced key must
have similar data types.
That is not true in your case : varchar(25) vs. int(11)
I tried all other ways but I found this useful as it worked for me. It is applicable also to the new MySQL version(v8.0)
CREATE TABLE Customers(
Customers_ID INT(10) PRIMARY KEY AUTO_INCREMENT,
Customers_name varchar(40) not null,
Customers_phone INT(10) not null,
Customers_email varchar(40) not null,
date_became_customer DATE not null,
login varchar(40) not null,
password varchar(40) not null,
other_details varchar(40) not null,
Customer_Types_code int(10) not null
REFERENCES Customer_types(Customer_Types_code));
Just change Geograpy_ID on Geography_Dim table to Geography_ID int(11) or change Geograpy_ID on Eval_Fact_Table to Geography_ID varchar(25) to solve the problem.
Error number: 3780 is due to incompatible foreign keys, the datatype of foreign key in each table must be same .
You could also not edit the primary key column in one table if it is a foreign key in another table.
For editing first drop the foreign key constraint in child table and then edit the primary key in the parent table and then again add constraints to child table.
HERE: Geography_ID varchar(25) vs Geography_ID int(11) are incompatible
First drop or alter this
FOREIGN KEY (Geography_ID) REFERENCES Geography_Dim (Geography_ID)
Geography_ID int(11) NOT NULL, and then add new column:
FOREIGN KEY (Geography_ID) REFERENCES Geography_Dim (Geography_ID)
with Geography_ID varchar(25)

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: Cannot add foreign key constraint between Parent and Children

I am utterly disappointed as I failed to pinpoint to the exact reason, why my table creation is failing when I am trying to create a Foreign Key relation between my two tables. The SQL queries that I am using to create the 2 tables are as under:
CREATE TABLE `OneMD_DEA_EMEA_STG_CUSTOMER` (
`Customer_Pkey` int(11) NOT NULL AUTO_INCREMENT,
`CustomerID` varchar(15) NOT NULL,
`DataType` varchar(10) NOT NULL,
`SourceSystemName` varchar(10) NOT NULL,
`SourceCountry` varchar(2) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`Category` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Customer_Pkey`,`CustomerID`),
UNIQUE KEY `CustomerID_UNIQUE` (`CustomerID`),
KEY `idx_OneMD_DEA_EMEA_STG_CUSTOMER` (`DataType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `STG_RELATION` (
`Relation_Pkey` int(11) NOT NULL AUTO_INCREMENT,
`RelationType` varchar(15) NOT NULL,
`SourceDataType` varchar(5) NOT NULL,
`SourceID` varchar(15) NOT NULL,
`TargetDataType` varchar(5) NOT NULL,
`TargetID` varchar(15) NOT NULL,
`RltnPrmryID` varchar(50) NOT NULL,
`SourceSystemName` varchar(10) DEFAULT NULL,
`SourceCountry` varchar(2) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`HCPHCOSubType` varchar(10) DEFAULT NULL,
`HCPHCOLinkType` varchar(10) DEFAULT NULL,
`HCOHCOSubType` varchar(10) DEFAULT NULL,
`HCOHCOLinkType` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Relation_Pkey`,`SourceID`,`TargetID`,`RltnPrmryID`),
UNIQUE KEY `Relation_Pkey_UNIQUE` (`Relation_Pkey`),
KEY `idx_STG_RELATION` (`RelationType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`),
KEY `Source_ID_idx` (`SourceID`),
KEY `Target_ID_idx` (`TargetID`),
CONSTRAINT `Source_ID` FOREIGN KEY (`SourceID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `Target_ID` FOREIGN KEY (`TargetID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `STG_RELATION_ROLE` (
`RltnRole_PKey` int(11) NOT NULL AUTO_INCREMENT,
`SourceSystemName` varchar(10) NOT NULL,
`ActivityID` varchar(15) NOT NULL,
`RltnFrgnID` varchar(50) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`SourceCountry` varchar(2) NOT NULL,
`HCPHCORoleType` varchar(10) DEFAULT NULL,
`HCPHCORoleField` varchar(10) DEFAULT NULL,
`HCPHCORole` varchar(10) DEFAULT NULL,
`HCPHCORoleStatus` varchar(20) DEFAULT NULL,
PRIMARY KEY (`RltnRole_PKey`,`SourceSystemName`,`ActivityID`,`RltnFrgnID`),
KEY `idx_STG_RELATION_ROLE` (`SrcDataRfrshDt`,`SourceSystemName`,`SourceCountry`,`EndDt`),
KEY `Rltn_Frgn_ID_idx` (`RltnFrgnID`),
CONSTRAINT `RltnFrgnID` FOREIGN KEY (`RltnFrgnID`) REFERENCES `STG_RELATION` (`RltnPrmryID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The Table RELATION got created successfully, but whenver I am trying to create the child table (RELATION_ROLE with parent as RELATION), the table creation is failing with the
Error 1215: Cannot Add Foreign Key Constraint
error message.
Am I missing something here?
Please note that CUSTOMER is the main table with child as RELATION (Customer_ID acting as Primary and Foreign Key) which further has a child RELATION_ROLE (RltnPrmryID is the Primary Key while RltnFrgnID is the foreign key.
Please help me to get the issue resolved.
Uh, there are quite a few problems there - in particular with your table designs.
First of all, the STG_RELATION.RltnPrmryID is not the left most field of any indexes. MySQL requires both endpoints of a foreign key to be the leftmost fields of an index. The leftmost fields are the ones that can be used for lookups. This is the direct reason of the error.
Secondly, the primary key of STG_RELATION table is a mess. The child table should reference the primary key or a unique key from the parent table. STG_RELATION.RltnPrmryID is neither, it is only part of the primary key. Relation_Pkey field being auto increment already uniquely identifies records within the STG_RELATION table, therefore this should be the PK and STG_RELATION_ROLE table should reference this column in the foreign key (obviously, you need to adjust the field type for this to work in STG_RELATION_ROLE). Indexes on integers are a lot more efficient than indexes on strings from a performance point of view.

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