mysql unable to add foreign key: error 1215 (hy000) - mysql

I am getting error 1215 (hy000): cannot add foreign key constraint then I run the following .sql file. The code below is also not creating the documents table, probably because it fails to create its foreign keys. Can anyone show me how to fix the code below so it will create the documents table including its foreign keys without throwing errors:
CREATE DATABASE IF NOT EXISTS petclinic;
GRANT ALL PRIVILEGES ON petclinic.* TO pc#localhost IDENTIFIED BY 'pc';
USE petclinic;
CREATE TABLE IF NOT EXISTS types (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80),
INDEX(name)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS documenttypes (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80),
INDEX(name)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS owners (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
address VARCHAR(255),
city VARCHAR(80),
telephone VARCHAR(20),
INDEX(last_name)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS pets (
id INT(4) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30),
birth_date DATE,
type_id INT(4) UNSIGNED NOT NULL,
owner_id INT(4) UNSIGNED NOT NULL,
INDEX(name),
FOREIGN KEY (owner_id) REFERENCES owners(id),
FOREIGN KEY (type_id) REFERENCES types(id)
) engine=InnoDB;
CREATE TABLE IF NOT EXISTS documents (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id int(4) NOT NULL,
type_id INT(4),
name varchar(200) NOT NULL,
description text NOT NULL,
filename varchar(200) NOT NULL,
content mediumblob NOT NULL,
content_type varchar(255) NOT NULL,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES owners(id),
FOREIGN KEY (type_id) REFERENCES documenttypes(id)
) engine=InnoDB;
I tried the advice at this link, but none of those suggestions work with this code. Can someone show me something that does work with this code?

The foreign key columns have to be the exact same data type as the original columns.
Try this:
CREATE TABLE IF NOT EXISTS documents (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id int(4) UNSIGNED NOT NULL,
type_id INT(4) UNSIGNED NOT NULL,
name varchar(200) NOT NULL,
description text NOT NULL,
filename varchar(200) NOT NULL,
content mediumblob NOT NULL,
content_type varchar(255) NOT NULL,
created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES owners(id),
FOREIGN KEY (type_id) REFERENCES documenttypes(id)
) engine=InnoDB;
Added UNSIGNED to client_id and UNSIGNED NOT NULL to type_id (the NOT NULL part in is not mandatory though)
sqlfiddle demo

Related

MARIADB: errno: 150 "Foreign key constraint is incorrectly formed

Im trying to create 3 different tables in mariadb. I am using the exact same code I used in my localhost and it worked.
The tables name are: location, artist and murals.
I first create the location table, then I create the artist table and finally I try create the murals table because this is where my foreign keys will be, but I keep getting the following error:
ERROR 1005 (HY000): Can't create table KOMA.murals (errno: 150 "Foreign key constraint is incorrectly formed")
Creating Location Table
Create TABLE location(
l_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(255),
city varchar(255) NOT NULL,
address varchar(255),
a_number int(10),
zipcode int(5)
);
Creating artist Table
Create TABLE artist(
a_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(255) NOT NULL );
Creating murals Table
CREATE table murals (
m_id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
title varchar(255) NOT NULL,
imageurl varchar(255) NOT NULL,
about varchar(255) NOT NULL,
year INT(4),
a_id INT(11),
l_id INT(11),
FOREIGN KEY (a_id) REFERENCES artist,
FOREIGN KEY (l_id) REFERENCES location
);
I would like to be able to create the last table with my foreign keys
When defining a foreign key, you need to point to the "parent" table and the referenced column; MySQL doesn't assume that the column has the same name.
CREATE TABLE `murals` (
`m_id` INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`imageurl` VARCHAR(255) NOT NULL,
`about` VARCHAR(255) NOT NULL,
`year` INT(4),
`a_id` INT(11),
`l_id` INT(11),
FOREIGN KEY (`a_id`) REFERENCES `artist`(`a_id`),
FOREIGN KEY (`l_id`) REFERENCES `location`(`l_id`)
);

MYSQL 1215 Cannot add Foreign Key Constraing

Problem is on the bounding table column GroupDim.FacultyID and FacultyDim.FacultyID, data types are identity BIGINT This data store for OLAP cube wherein Rating_facts stores result of question which i exploring. table without signature Dim is transitional and serve for additional data for analysis.Maybe it is needs to divide this table?
DROP TABLE IF EXISTS BlockDim;
CREATE TABLE BlockDim (
BlockKey bigint NOT NULL AUTO_INCREMENT,
BlockID bigint NOT NULL,
BlockName varchar(32) NOT NULL,
PRIMARY KEY (BlockKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS FacultyDim;
CREATE TABLE FacultyDim (
FacultyKey bigint NOT NULL AUTO_INCREMENT,
FacultyID bigint NOT NULL,
FacultyName varchar(32) NOT NULL,
PRIMARY KEY (FacultyKey, FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS `Group`;
CREATE TABLE `Group` (
GroupID bigint NOT NULL,
FacultyID bigint NOT NULL,
GroupName varchar(32) NOT NULL,
PRIMARY KEY (GroupID),
FOREIGN KEY (FacultyID) REFERENCES FacultyDim(FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS Subblock;
CREATE TABLE Subblock (
SubblockKey bigint NOT NULL AUTO_INCREMENT,
SubblockID bigint NOT NULL,
BlockID bigint NOT NULL,
SubblockName varchar(32) NOT NULL,
PRIMARY KEY (SubblockKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS Paragraph;
CREATE TABLE Paragraph (
ParagraphKey bigint NOT NULL AUTO_INCREMENT,
ParagraphID bigint NOT NULL,
SubblockID bigint NOT NULL,
ParagraphName varchar(64) NOT NULL,
PRIMARY KEY (ParagraphKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS RatingDim;
CREATE TABLE RatingDim (
RatingKey bigint NOT NULL AUTO_INCREMENT,
RatingID bigint NOT NULL,
ParagraphID bigint NOT NULL,
Score double NOT NULL,
StageOfApprove int NOT NULL,
Comment varchar(128) NOT NULL,
`Date` DATE NOT NULL,
PRIMARY KEY (RatingKey)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS TimeDim;
CREATE TABLE TimeDim (
TimeKey bigint NOT NULL AUTO_INCREMENT,
`Date` DATE NOT NULL,
DayOfWeek varchar(16) NOT NULL,
`Month` varchar(16) NOT NULL,
`Year` varchar(4) NOT NULL,
PRIMARY KEY (`TimeKey`)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS Rating_Fact;
CREATE TABLE Rating_Fact (
TimeKey bigint NOT NULL,
BlockKey bigint NOT NULL,
FacultyKey bigint NOT NULL,
RatingKey bigint NOT NULL,
PopularBlock bigint NOT NULL,
AvgFacultyScore bigint NOT NULL,
StudentsMaxRating bigint NOT NULL,
StudentsNotApprovedRating bigint NOT NULL,
PRIMARY KEY (TimeKey,BlockKey,FacultyKey,RatingKey),
FOREIGN KEY (TimeKey) REFERENCES TimeDim(TimeKey),
FOREIGN KEY (BlockKey) REFERENCES BlockDim(BlockKey),
FOREIGN KEY (FacultyKey) REFERENCES FacultyDim(FacultyKey),
FOREIGN KEY (RatingKey) REFERENCES RatingDim(RatingKey)
)ENGINE=InnoDB;
First you have check your table architecture.then try below two solutions
Solution 1:-
DROP TABLE IF EXISTS FacultyDim;
CREATE TABLE FacultyDim (
FacultyKey bigint NOT NULL AUTO_INCREMENT,
FacultyID bigint NOT NULL,
FacultyName varchar(32) NOT NULL,
PRIMARY KEY (FacultyKey, FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS `Group`;
CREATE TABLE `Group` (
GroupID bigint NOT NULL,
FacultyID bigint NOT NULL,
GroupName varchar(32) NOT NULL,
PRIMARY KEY (GroupID),
FOREIGN KEY (FacultyID) REFERENCES FacultyDim(FacultyID,FacultyKey)
)ENGINE=InnoDB;
Solution 2:-
DROP TABLE IF EXISTS FacultyDim;
CREATE TABLE FacultyDim (
FacultyKey bigint NOT NULL AUTO_INCREMENT,
FacultyID bigint NOT NULL,
FacultyName varchar(32) NOT NULL,
PRIMARY KEY (FacultyID)
)ENGINE=InnoDB;
DROP TABLE IF EXISTS `Group`;
CREATE TABLE `Group` (
GroupID bigint NOT NULL,
FacultyID bigint NOT NULL,
GroupName varchar(32) NOT NULL,
PRIMARY KEY (GroupID),
FOREIGN KEY (FacultyID) REFERENCES FacultyDim(FacultyID)
)ENGINE=InnoDB;

Cannot Add foreign key constraint Error 1215

I am using Workbench 6.0 and having a frustrating issue I am new to SQl and would like to keep this as simple as possible at this point, I believe my tables are ordered properly to add contraints except for my TICKET table, no idea how to find what foreign key is having problems.
CREATE TABLE IF NOT EXISTS ACTION_TYPE (
ActionCode int primary key,
Description char(50) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS OFFICER (
PersonnelNo int primary key,
OfficerLName char(50) not null,
OfficerFName char(50) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS DRIVER (
DriverLicenseNo int primary key,
DriverLastName char(50) not null,
DriverFirstName char(50) not null,
DriverAddress char(50) not null,
DriverCity char(50) not null,
DriverProv char(50) not null,
DriverPostalCode varchar(6) not null,
DriverGender char(1) not null,
DriverBirthDate Date not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS REGISTERED_OWNER (
RegOwnerID int primary key auto_increment,
RegOwnerLName char(50) not null,
RegOwnerFName char(50) not null,
RegOwnerAddress char(50) not null,
RegOwnerCity char(50) not null,
RegOwnerProv char(50) not null,
RegOwnerPostalCode varchar(6) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VEHICLE_TYPE (
VehicleType int primary key,
VehicleDescription char(50) not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VEHICLE (
VehicleLicense int primary key,
ProvinceIssued char(2) not null,
VehicleYear int not null,
VehicleMake char(10) not null,
VehicleType int not null,
index (VehicleType),
foreign key (VehicleType)
references VEHICLE_TYPE (VehicleType)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS TICKET ( <-----this table calling the error
TicketNo int primary key auto_increment,
TicketDateTime datetime not null,
TicketLocationCity char(50) not null,
TicketLocationProv char(50) not null,
TicketLocationRoad char(50) not null,
PersonnelNo int not null,
VehicleLicense int not null,
ActionCode int not null,
RegOwnerID int not null,
DriversLicenseNo int not null,
index (PersonnelNo),
foreign key (PersonnelNo)
references OFFICER (PersonnelNo),
index (VehicleLicense),
foreign key (VehicleLicense)
references VEHICLE (VehicleLicense),
index (ActionCode),
foreign key (ActionCode)
references ACTION_TYPE (ActionCode),
index (RegOwnerID),
foreign key (RegOwnerID)
references REGISTERED_OWNER (RegOwnerID),
index (DriversLicenseNo),
foreign key (DriversLicenseNo)
references DRIVER (DriversLicenseNo)
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VIOLATION_TYPE (
ViolationCode int primary key auto_increment,
ViolationDesc char(50) not null,
ViolationCurrFineAmt int not null
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS VIOLATION (
ViolationNo int primary key auto_increment,
TicketNo int not null,
ViolationCode int not null,
AppliedFineAmount int not null,
index (TicketNo),
foreign key (TicketNo)
references TICKET (TicketNo),
index (ViolationCode),
foreign key (ViolationCode)
references VIOLATION_TYPE (ViolationCode)
)ENGINE=InnoDB;
Spelling mistake on DriverLicenseNo in TICKET table ane
DriversLicenseNo in DRIVER table

How to create table in mysql database with foreign key which is primary key of another table?

CREATE TABLE employee_detail(
e_id int auto_increment,
name varchar(20) not null,
address varchar(20) not null,
status varchar(200) not null,
primary key (e_id),
);
This is my first table(employee_login)and I want e_id as a foreign key in my next table (login) below
CREATE TABLE login(
login_id int auto_increment,
username varchar(20) not null,
password varchar(20) not null,
primary key (login_id),
e_id references employee_detail(e_id)
);
You can do it like follows :
CREATE TABLE person (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name CHAR(60) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE shirt (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
style ENUM('t-shirt', 'polo', 'dress') NOT NULL,
color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL,
owner SMALLINT UNSIGNED NOT NULL REFERENCES person(id),
PRIMARY KEY (id)
);
I hope you understand the create table code. owner in the shirt table is the foreign key referencing id from the person table
You have several mistakes. You were missing e_id column in your Login Table, you can't add a foreign key without adding employee_detail's primary key column which in this case is e_id. Also you can't use password as a column name since it is a preestablished query you'll need to use something else like "pass".
CREATE TABLE employee_detail(
e_id int auto_increment,
name varchar(20) not null,
address varchar(20) not null,
status varchar(200) not null,
primary key (e_id));
CREATE TABLE login(
login_id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(20) NOT NULL,
pass VARCHAR(20) NOT NULL,
e_id INT,
FOREIGN KEY (e_id) REFERENCES employee_detail(e_id)
);

MySQL error while creating tables

I have an error in my database
Error: Invalid structure on line 18. Refer to our Manual (PHPMYADMIN)
I use (WAMPSERVER 2 32bits)
-PHPMYADMIN
- MYSQL 5.5.6
- PHP 5
Although i need to use InnoDB (ENGINE=InnoDB)
thanks to help me. Take a look at the structure... the variable name meaning is not important.
Here's my code:
DROP TABLE IF EXISTS Adresse;
DROP TABLE IF EXISTS Telephone;
DROP TABLE IF EXISTS Personne;
DROP TABLE IF EXISTS TelPers;
DROP TABLE IF EXISTS Specialiste;
DROP TABLE IF EXISTS Patient;
DROP TABLE IF EXISTS ListePatient;
DROP TABLE IF EXISTS Produit;
DROP TABLE IF EXISTS Medicament;
DROP TABLE IF EXISTS Materiel;
DROP TABLE IF EXISTS Panier;
CREATE TABLE Adresse(
idAdresse INT(100) NOT NULL PRIMARY KEY AUTO_INCREMENT,
num INT(5) NOT NULL,
rue VARCHAR(30) NOT NULL,
ville VARCHAR(15) NOT NULL,
postal VARCHAR(6) NOT NULL
)ENGINE=InnoDB;
CREATE TABLE Telephone(
idTel INT(100) NOT NULL PRIMARY KEY AUTO_INCREMENT,
typeTel VARCHAR(15) NOT NULL,
ind INT(3) NOT NULL,
quartier INT(3) NOT NULL,
num INT(4) NOT NULL,
)ENGINE=InnoDB;
CREATE TABLE Personne(
idPersonne INT(100) PRIMARY KEY NOT NULL AUTO_INCREMENT,
nom VARCHAR(15) NOT NULL,
prenom VARCHAR(15) NOT NULL,
idTel INT(100) NOT NULL,
idAdresse INT(100) NOT NULL,
FOREIGN KEY(idAdresse) REFERENCES Adresse(idAdresse),
FOREIGN KEY(idTel) REFERENCES Telephone(idTel)
)ENGINE=InnoDB;
CREATE TABLE TelPers(
idPersonne INT(100) PRIMARY KEY NOT NULL,
idTel INT(100) PRIMARY KEY NOT NULL,
FOREIGN KEY(idPersonne) REFERENCES Personne(idPersonne),
FOREIGN KEY(idTel) REFERENCES Telephone(idTel)
)ENGINE=InnoDB;
CREATE TABLE Specialiste(
login VARCHAR(10) PRIMARY KEY NOT NULL PRIMARY KEY,
password VARCHAR(10) NOT NULL,
profession VARCHAR(20) NOT NULL,
idListeP INT(5),
idPanier INT(5),
idPersonne INT(100),
FOREIGN KEY(idPersonne) REFERENCES Personne(idPersonne)
)ENGINE=InnoDB;
CREATE TABLE Patient(
idPatient INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
sexe CHAR NOT NULL,
anniv DATE,
assurance INT(3) NOT NULL,
idPersonne INT(100),
FOREIGN KEY(idPersonne) REFERENCES Personne(idPersonne)
)ENGINE=InnoDB;
CREATE TABLE ListePatient(
idListeP INT(5) NOT NULL PRIMARY KEY,
idPatient INT(10)NOT NULL PRIMARY KEY,
FOREIGN KEY(idListeP) REFERENCES Specialiste(idListeP),
FOREIGN KEY(idPatient) REFERENCES Patient(idPatient)
)ENGINE=InnoDB;
CREATE TABLE Produit(
idProduit INT(100) NOT NULL PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(50) NOT NULL,
descr VARCHAR(255) NOT NULL,
prix DECIMAL(5,2) NOT NULL,
qte INT(100) NOT NULL
)ENGINE=InnoDB;
CREATE TABLE Medicament(
idMedic INT(100)NOT NULL PRIMARY KEY AUTO_INCREMENT,
marque VARCHAR(10) NOT NULL,
typeMed VARCHAR(10) NOT NULL,
idProduit INT(100) NOT NULL,
FOREIGN KEY(idProduit) REFERENCES Produit(idProduit)
)ENGINE=InnoDB;
CREATE TABLE Materiel(
idMateriel INT(100) NOT NULL PRIMARY KEY AUTO_INCREMENT,
rabais INT(99) NOT NULL,
idProduit INT(100) NOT NULL,
FOREIGN KEY(idProduit) REFERENCES Produit(idProduit)
)ENGINE=InnoDB;
CREATE TABLE Panier(
idPanier INT(5) NOT NULL PRIMARY KEY,
idProduit INT(100) NOT NULL PRIMARY KEY,
FOREIGN KEY(idPanier) REFERENCES Specialiste(idPanier),
FOREIGN KEY(idProduit) REFERENCES Produit(idProduit)
)ENGINE=InnoDB;
THANKS FOR YOUR HELP! :D
In Telephone declaration there is a comma (,) before closing )
In TelPers there are two primary keys
In Specialiste there is PRIMARY KEY twice in login column
In ListePatien there are two primary keys
In Panier there are two primary keys
To define a PRIMARY key on two columns use
CREATE TABLE Panier(
idPanier INT(5) NOT NULL,
idProduit INT(100) NOT NULL,
PRIMARY KEY (`idPanier`,`idProduit`),
FOREIGN KEY(idPanier) REFERENCES Specialiste(idPanier),
FOREIGN KEY(idProduit) REFERENCES Produit(idProduit)
)ENGINE=InnoDB;
(same on other tables)