mysql - cannot add foreign key constraint when creating a table - mysql

I'm new to sql.
I get this error when I try to create foreign keys:
cannot add foreign key constraint
when I'm trying to create the ORDERS table. here is my code:
drop database if exists Company;
create database Company;
use Company;
create table WORKERS(w_id varchar(4), w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4), customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
create table WAREHOUSE(m_id int unsigned primary key, describes varchar(20) not null, fl char(1));
create table ITEM(p_id int(4) unsigned primary key, p_name varchar(15) not null, p_price float not null);
create table INVENTORY(in_id int auto_increment primary key, m_id int unsigned not null, p_id int(4) unsigned not null, amount int not null,
foreign key (m_id) references WAREHOUSE(m_id),
foreign key (p_id) references ITEM(p_id)
);
create table ORDERS(o_id int auto_increment primary key, customer_id varchar(4),
p_id int(4) unsigned, w_id varchar(4), amount int unsigned not null,
date_of_order date not null,
foreign key (p_id) references ITEM(p_id),
foreign key (w_id) references WORKERS(w_id),
foreign key (customer_id) references CUSTOMERS(customer_id)
);
I put the ORDERS (where I have the problem) on different lines to make it easier to you to read.
I search here for an answer, but didn't found anything specific that answer my question.
anyone got any idea what the problem is? thank you!

The problem is that you are trying to create a FOREIGN KEY relationship to a field in the WORKERS and CUSTOMERS tables that aren't set up as a PRIMARY KEY.
The FOREIGN KEY needs to be pointing to a PRIMARY KEY. Change your create script to the following:
create table WORKERS(w_id varchar(4) primary key, w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4) primary key, customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
A word of caution, though. I would recommend not using VARCHAR (4) as a PRIMARY KEY field. I would recommend using an INT AUTO_INCREMENT instead.

The column of the referenced table should be declared as primary key to assign a foreign key. For your orders table, WORKERS(w_id) and CUSTOMERS(customer_id) are not declared as primary key, hence you get the error.
Modified Statements:
drop database if exists Company;
create database Company;
use Company;
create table WORKERS(w_id varchar(4) primary key, w_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique);
create table CUSTOMERS(customer_id varchar(4) primary key, customer_name varchar(20) not null, telephone varchar(12), e_mail varchar(35) unique, credit bool);
create table WAREHOUSE(m_id int unsigned primary key, describes varchar(20) not null, fl char(1));
create table ITEM(p_id int(4) unsigned primary key, p_name varchar(15) not null, p_price float not null);
create table INVENTORY(in_id int auto_increment primary key, m_id int unsigned not null, p_id int(4) unsigned not null, amount int not null,
foreign key (m_id) references WAREHOUSE(m_id),
foreign key (p_id) references ITEM(p_id)
);
create table ORDERS(o_id int auto_increment primary key, customer_id varchar(4),
p_id int(4) unsigned, w_id varchar(4), amount int unsigned not null,
date_of_order date not null,
foreign key (p_id) references ITEM(p_id),
foreign key (w_id) references WORKERS(w_id),
foreign key (customer_id) references CUSTOMERS(customer_id)
);
SQLFiddle Demo

Related

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.

mysql #1005 errno 150

I'm creating some mysql code with phpmyadmin for a school project and am getting the error "#1005 - Can't create table world_cup.goal (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)".
I can't figure out why I'm getting the error. If I delete the GOAL entity, it still gives the error, but with the CARD entity. In fact, it doesn't like the last 4 entities I created. It has to do with the the foreign key I think.
WHAT I'VE TRIED:
making sure that all the FK and the referenced PK are the same datatype. They match perfectly.
I can't think of anything else to try.
This is due tomorrow so any help would be greatly appreciated! Thanks!
Here is the code:
DROP DATABASE IF EXISTS WORLD_CUP;
CREATE DATABASE WORLD_CUP;
USE WORLD_CUP;
CREATE TABLE TEAM(
Cid varchar(2) NOT NULL,
Continent varchar(20),
Confederation varchar(20) NOT NULL,
Population int,
CName varchar(20) NOT NULL,
PRIMARY KEY(Cid),
UNIQUE(CName)
);
CREATE TABLE PLAYER(
PCid varchar(2) NOT NULL,
Pno int NOT NULL,
Position varchar(20) NOT NULL,
Pfname varchar(20) NOT NULL,
Plname varchar(20) NOT NULL,
Weight int,
Height int,
Club varchar(20),
BDayMonth int,
BDayDay int,
BDayYear int,
PJName varchar(22) NOT NULL,
PRIMARY KEY(PCid, PNo),
FOREIGN KEY (PCid) REFERENCES TEAM(Cid)
);
CREATE TABLE GAME(
Gid varchar(2) NOT NULL,
Score1 int,
Score2 int,
Stadium varchar(20),
Team1Cid varchar(20) NOT NULL,
Team2Cid varchar(20) NOT NULL,
GMonth int,
GDay int,
GYear int,
GType char(1) NOT NULL,
KOGSubtype char(1),
PRIMARY KEY(Gid, Team1Cid, Team2Cid),
FOREIGN KEY(Team1Cid) REFERENCES TEAM(Cid),
FOREIGN KEY(Team2Cid) REFERENCES TEAM(Cid)
);
CREATE TABLE STADIUM(
Sid varchar(2) NOT NULL,
Sname varchar(20) NOT NULL,
Capacity int,
City varchar(20),
PRIMARY KEY(Sid)
);
CREATE TABLE GOAL(
GPno int NOT NULL,
GMinute varchar(6) NOT NULL,
GoalType char NOT NULL,
GGid varchar(2) NOT NULL,
PRIMARY KEY(GPno, GGid, GMinute) ,
FOREIGN KEY (GPno) REFERENCES PLAYER(Pno),
FOREIGN KEY (GGid) REFERENCES GAME(Gid)
);
CREATE TABLE CARD(
CPno int NOT NULL,
CMinute varchar(6) NOT NULL,
Color char(1) NOT NULL,
CGid varchar(2) NOT NULL,
PRIMARY KEY(CPno, CGid, CMinute) ,
FOREIGN KEY(CPno) REFERENCES PLAYER(Pno),
FOREIGN KEY(CGid) REFERENCES GAME(Gid)
);
CREATE TABLE SUBSTITUTE(
PInNo int NOT NULL,
POutNo int NOT NULL,
SMinute varchar(6) NOT NULL,
SGid varchar(2) NOT NULL,
SCid varchar(2) NOT NULL,
PRIMARY KEY(PInNo, POutNo, SMinute, SGid, SCid),
FOREIGN KEY (PInNo) References PLAYER(Pno),
FOREIGN KEY (POutNo) References PLAYER(Pno),
FOREIGN KEY (SGid) References GAME(Gid),
FOREIGN KEY (SCid) References TEAM(Cid)
);
CREATE TABLE STARTINGLINEUP(
SPno int NOT NULL,
PCid varchar(2) NOT NULL,
PGid varchar(2) NOT NULL,
PRIMARY KEY(SPno, PCid, PGid),
FOREIGN KEY (SPno) REFERENCES PLAYER(Pno),
FOREIGN KEY(PCid) REFERENCES TEAM(Cid),
FOREIGN KEY (PGid) REFERENCES GAME(Gid)
);
It's because the primary key on PLAYER is composite, so the foreign key that points to it has to be composite too.
My version of GOAL - note addition of GPCid and its inclusion in the foreign key:
CREATE TABLE GOAL(
GPCid varchar(2) not null,
GPno int NOT NULL,
GMinute varchar(6) NOT NULL,
GoalType char NOT NULL,
GGid varchar(2) NOT NULL,
PRIMARY KEY(GPno, GGid, GMinute) ,
FOREIGN KEY (GPCid,GPno) REFERENCES PLAYER(PCid,Pno),
FOREIGN KEY (GGid) REFERENCES GAME(Gid)
);
And similarly for CARD etc.

Can't figure out why mySql database syntax won't compile

I'm getting this syntax error for a DB I am writing for my own personal project and am unsure why this error is occuring, any help would be much appreciated! The desired result is just compilation at this point, and the error is a simple syntax error.
The problem table is the Team table.
Error Code: 1215: Cannot add foreign key contraint.
-- CREATE DATABASE basketBall;
DROP TABLE LEAGUE;
-- DROP TABLE TEAM;
DROP TABLE SESSION;
CREATE TABLE LEAGUE (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL UNIQUE,
PRIMARY KEY(id)
);
CREATE TABLE SESSION (
year INT NOT NULL,
season VARCHAR(50) NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(year, season, division),
CONSTRAINT chk_season CHECK (season IN ('Fall', 'Winter', 'Spring', 'Summer'))
);
CREATE TABLE TEAM (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
season VARCHAR(50) NOT NULL,
year INT NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(season) REFERENCES SESSION(season),
FOREIGN KEY(year) REFERENCES SESSION(year),
FOREIGN KEY(division) REFERENCES SESSION(division)
);
CREATE TABLE PLAYER (
id INT NOT NULL AUTO_INCREMENT,
fname VARCHAR(30) NOT NULL,
lname VARCHAR(30) NOT NULL,
lid INT,
PRIMARY KEY(id)
);
CREATE TABLE GAME (
id INT NOT NULL AUTO_INCREMENT,
time VARCHAR(5),
court VARCHAR(20),
date DATE,
PRIMARY KEY(id)
);
CREATE TABLE STATS (
pid INT NOT NULL,
gid int NOT NULL,
pts INT NOT NULL,
fgm INT NOT NULL,
fga INT NOT NULL,
fta INT NOT NULL,
ftm INT NOT NULL,
3fgm INT NOT NULL,
3fga INT NOT NULL,
oreb INT NOT NULL,
dreb INT NOT NULL,
ast INT NOT NULL,
stl INT NOT NULL,
blk INT NOT NULL,
turnover INT NOT NULL,
eff INT NOT NULL,
pf INT NOT NULL,
min INT NOT NULL,
PRIMARY KEY(pid, gid),
FOREIGN KEY(pid) REFERENCES PLAYER(id),
FOREIGN KEY(gid) REFERENCES GAME(id)
);
CREATE TABLE Players_on_Team (
tid INT NOT NULL,
pid INT NOT NULL,
PRIMARY KEY(tid, pid),
FOREIGN KEY(tid) REFERENCES TEAM(id)
);
CREATE TABLE League_Sessions (
lid INT NOT NULL,
year INT NOT NULL,
season VARCHAR(50) NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(lid, year, season, division),
FOREIGN KEY(lid) REFERENCES LEAGUE(id)
);
A column that you reference in a foreign key must be indexed. These two foreign keys in TEAM:
FOREIGN KEY(season) REFERENCES SESSION(season),
FOREIGN KEY(division) REFERENCES SESSION(division)
refer to columns that don't have indexes of their own. They're parts of a multi-column index, but only a prefix of a multi-column index acts as an index on those specific columns.
You could add separate indexes on the season and division columns to the SESSION table. But it would probably be more appropriate to make a multi-column foreign key:
FOREIGN KEY (year, season, division) REFERENCES SESSION(year, season, division)
I just tried it and it executes without any errors.

Error: Can't create table 'Goober.Employee' (errno: 150)

I get this following error for some reason, and I know it has to do with the foreignkey I just added "UsesTruck" However I don't know WHAT it is I did wrong.. I have included only the tables I think are important for this issue.
CREATE TABLE Employee (
EmployeeID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
UsesTruck CHAR(20) NULL,
FOREIGN KEY (UsesTruck) REFERENCES Truck(LicensePlate),
PRIMARY KEY (EmployeeID));
CREATE TABLE Truck (
LicensePlate CHAR(20) NULL,
color VARCHAR(45) NULL,
capacity VARCHAR(45) NULL,
PRIMARY KEY (LicensePlate));
CREATE TABLE Shifts (
ShiftTime VARCHAR(15) NOT NULL,
PRIMARY KEY (ShiftTime));
CREATE TABLE Reservation (
ReservNum INT NOT NULL,
ReserveDate VARCHAR(45) NULL,
PickupTime VARCHAR(45) NOT NULL,
NumOfPassengers INT NULL,
sheduledTime VARCHAR(45) NULL,
ActualPickupTime VARCHAR(45),
ActualTime VARCHAR(45),
PricePaid VARCHAR(45),
DriverHourlyRate DECIMAL(7,2) NULL,
PassEmployeeHourlyRate DECIMAL (7,2) NULL,
DriverSalary VARCHAR(10),
PassEmployeeSalary VARCHAR(10),
Customer_CustomerID INT,
Truck_LicensePlate char(20) NULL,
Employee_EmployeeID_Driver INT,
Location_Address_Pickup VARCHAR(100),
Employee_EmployeeID_Passenger INT,
Location_Address_Drop VARCHAR(100),
PRIMARY KEY (ReservNum),
FOREIGN KEY (Customer_CustomerID) REFERENCES Customer (CustomerID),
FOREIGN KEY (Truck_LicensePlate) REFERENCES Truck (LicensePlate),
FOREIGN KEY (Employee_EmployeeID_Driver) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Pickup) REFERENCES Location (Address),
FOREIGN KEY (Employee_EmployeeID_Passenger) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Drop) REFERENCES Location (Address));
Try to run create Truck table firstly.

Documentation #1005 - Can't create table 'comparein' (errno: 150)

Where is the problem? i am trying to create the table comparein using the composed primary key from the table Episodi but there should be a problem that i can t see..
the primary key from the table is a combination of "numero" and "titolo_episodio"
create table Autori(
id_autore int auto_increment primary key,
nome varchar(15) not null,
cognome varchar(15) not null,
nome_arte varchar (15)
) ENGINE=InnoDB;
create table Serie(
nome varchar(25) primary key,
id_autore int(6),
descrizione varchar(400),
FOREIGN KEY (id_autore)REFERENCES Autori(id_autore)
) ENGINE=InnoDB;
create table Episodi(
titolo_episodio varchar(25) not null,
numero int not null,
durata time not null,
data_trasmissione date not null,
nome_serie varchar(25),
PRIMARY KEY(titolo_episodio,numero),
FOREIGN KEY (nome_serie)REFERENCES Serie(nome)
) ENGINE=InnoDB;
create table Personaggi(
id_pers int auto_increment primary key,
nome varchar(15) not null,
cognome varchar(15),
nazionalita varchar (15),
nome_serie varchar(25),
FOREIGN KEY (nome_serie)REFERENCES Serie(nome)
) ENGINE=InnoDB;
create table Utenti(
nickname varchar(15) primary key,
nazionalita varchar(15) not null,
mail varchar(25) not null,
pwd varchar(15) not null,
amministratore bool default 0 not null
) ENGINE=InnoDB;
create table Generi(
genere varchar(15) primary key
) ENGINE=InnoDB;
create table comparein(
id_pers int not null,
numero int not null,
titolo_episodio varchar(25),
FOREIGN KEY (id_pers)REFERENCES Personaggi(id_pers),
FOREIGN KEY (numero,titolo_episodio)REFERENCES Episodi(numero,titolo_episodio),
primary key(id_pers,numero,titolo_episodio)
) ENGINE=InnoDB;
I think you need to reference the PK columns in the same order as the primary key was defined. So instead of
FOREIGN KEY (numero,titolo_episodio)REFERENCES Episodi(numero,titolo_episodio)
use
FOREIGN KEY (titolo_episodio, numero) REFERENCES Episodi(titolo_episodio, numero)
SQLFiddle: http://sqlfiddle.com/#!2/363bd