MySQL ERROR 1005 : Can't create table (errno: 150) - mysql

Im a beginner in mysql, i don't understand my mistake
its a problem with the foreign key of "membre" and "club".
CREATE TABLE club(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) UNIQUE NOT NULL,
INDEX club_nom_index (nom),
adresse_id INT NOT NULL,
nom_du_responsable VARCHAR(255) NULL,
FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);
CREATE TABLE membre(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
prénom VARCHAR(255) NOT NULL,
adresse_id INT NOT NULL,
club_id INT NOT NULL,
rang_qualification INT NOT NULL,
numéro_téléphone VARCHAR(255) NULL,
courriel VARCHAR(255) UNIQUE NULL,
INDEX membre_courriel_index (courriel),
nb_parties_gagnées INT NOT NULL,
nb_parties_perdues INT NOT NULL,
nb_parties_nulles INT NOT NULL,
FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),
INDEX nom_prénom_membre_index (nom, prénom),
CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);
CREATE TABLE tournoi(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
INDEX tournoi_nom_index (nom),
club_id INT NOT NULL,
date_début DATE NOT NULL,
date_fin DATE NOT NULL,
FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),
CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);
CREATE TABLE partie(
id INT PRIMARY KEY AUTO_INCREMENT,
membre1_id INT NOT NULL,
membre2_id INT NOT NULL,
résultat INT NULL,
date_début DATE NULL,
heure_début TIME NULL,
id_tournoi INT NOT NULL,
FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),
INDEX membres_index(membre1_id, membre2_id),
CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);
CREATE TABLE adresse(
id INT PRIMARY KEY AUTO_INCREMENT,
adresse VARCHAR(255) NOT NULL,
rue VARCHAR(255) NOT NULL,
ville VARCHAR(255) NOT NULL,
code_postal CHAR(6) NULL,
INDEX adresse_code_index (code_postal),
province_état CHAR(3) NULL,
pays CHAR(2) NOT NULL,
CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
[[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);
CREATE TABLE rang(
qualification INT PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(255) UNIQUE NULL
);
I was expecting the program to run but it keeps telling me that there is a problem with the foreign key in "membre" and "club".

You must change the order of the create statements.
First table rang and second table adresse, because the other tables have references to these tables:
CREATE TABLE rang(
qualification INT PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(255) UNIQUE NULL
);
CREATE TABLE adresse(
id INT PRIMARY KEY AUTO_INCREMENT,
adresse VARCHAR(255) NOT NULL,
rue VARCHAR(255) NOT NULL,
ville VARCHAR(255) NOT NULL,
code_postal CHAR(6) NULL,
INDEX adresse_code_index (code_postal),
province_état CHAR(3) NULL,
pays CHAR(2) NOT NULL,
CONSTRAINT code_postal_chk CHECK (code_postal REGEXP '^[A-Z]
[[:digit:]][A-Z][[:digit:]][A-Z][[:digit:]]$')
);
CREATE TABLE club(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) UNIQUE NOT NULL,
INDEX club_nom_index (nom),
adresse_id INT NOT NULL,
nom_du_responsable VARCHAR(255) NULL,
FOREIGN KEY club_adresse_id_fk (adresse_id) REFERENCES adresse(id)
);
CREATE TABLE membre(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
prénom VARCHAR(255) NOT NULL,
adresse_id INT NOT NULL,
club_id INT NOT NULL,
rang_qualification INT NOT NULL,
numéro_téléphone VARCHAR(255) NULL,
courriel VARCHAR(255) UNIQUE NULL,
INDEX membre_courriel_index (courriel),
nb_parties_gagnées INT NOT NULL,
nb_parties_perdues INT NOT NULL,
nb_parties_nulles INT NOT NULL,
FOREIGN KEY membre_adresse_id_fk (adresse_id) REFERENCES adresse(id),
FOREIGN KEY membre_club_id_fk (club_id) REFERENCES club(id),
FOREIGN KEY membre_rang_qualification_fk (rang_qualification) REFERENCES rang(qualification),
INDEX nom_prénom_membre_index (nom, prénom),
CONSTRAINT parties_gagnées_chk CHECK (nb_parties_gagnées >= 0),
CONSTRAINT parties_perdues_chk CHECK (nb_parties_perdues >= 0),
CONSTRAINT parties_nulles_chk CHECK(nb_parties_nulles >= 0)
);
CREATE TABLE tournoi(
id INT PRIMARY KEY AUTO_INCREMENT,
nom VARCHAR(255) NOT NULL,
INDEX tournoi_nom_index (nom),
club_id INT NOT NULL,
date_début DATE NOT NULL,
date_fin DATE NOT NULL,
FOREIGN KEY tournoi_club_id_fk (club_id) REFERENCES club(id),
CONSTRAINT nom_date_unq UNIQUE (nom, date_début)
);
CREATE TABLE partie(
id INT PRIMARY KEY AUTO_INCREMENT,
membre1_id INT NOT NULL,
membre2_id INT NOT NULL,
résultat INT NULL,
date_début DATE NULL,
heure_début TIME NULL,
id_tournoi INT NOT NULL,
FOREIGN KEY partie_membre1_id_fk (membre1_id) REFERENCES membre(id),
FOREIGN KEY partie_membre2_id_fk (membre2_id) REFERENCES membre(id),
FOREIGN KEY partie_tournoi_id_fk (id_tournoi) REFERENCES tournoi(id),
INDEX membres_index(membre1_id, membre2_id),
CONSTRAINT résultat_chk CHECK (résultat >= 0 AND résultat <= 2),
CONSTRAINT membres_unq UNIQUE (membre1_id, membre2_id),
CONSTRAINT date_heure_unq UNIQUE (date_début, heure_début)
);

Related

MySQL v5.7/5.6 Cannot add Foreign Key constraint

I tried putting this through db-fiddle and SQL fiddle Keep getting "Schema Error: Error: ER_CANNOT_ADD_FOREIGN: Cannot add foreign key constraint"
Everything works until I put the last table.
'''
CREATE TABLE User (
User_ID INT NOT NULL,
First_Name VARCHAR(30) NOT NULL,
Last_Name VARCHAR(30) NOT NULL,
Address_1 VARCHAR(100) NOT NULL,
Address_2 VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
State VARCHAR(100) NOT NULL,
Zip VARCHAR(25) NOT NULL,
Mobile_Phone VARCHAR(30) NOT NULL,
PRIMARY KEY (User_ID)
);
CREATE TABLE Bagel (
Bagel_ID INT NOT NULL,
Bagel_Name VARCHAR(30) NOT NULL,
Bagel_Description VARCHAR(30) NOT NULL,
Bagel_Price NUMERIC(65,2) NOT NULL,
PRIMARY KEY(Bagel_ID)
);
CREATE TABLE Bagel_Order (
Bagel_Order_ID INT NOT NULL,
User_ID INT NOT NULL,
Order_Date TIMESTAMP,
Delivery_Fee NUMERIC(50 , 2) NOT NULL,
Special_Notes CHAR,
PRIMARY KEY (Bagel_Order_ID),
FOREIGN KEY (User_ID) REFERENCES User (User_ID)
);
CREATE TABLE Bagel_Order_Line_Item (
Bagel_Order_ID INT NOT NULL,
Bagel_ID INT NOT NULL,
Bagel_Quantity INT NOT NULL,
PRIMARY KEY(Bagel_Order_ID, Bagel_ID),
FOREIGN KEY(Bagel_Order_ID) REFERENCES
Bagel_Order_Line_Item(Bagel_Order_ID),
FOREIGN KEY(Bagel_ID) REFERENCES Bagel(Bagel_ID)
);
'''

"Cannot add foreign key constraint" error in MySQL

I keep getting this error and I am not sure what I'm doing wrong. I
Error SQL query:
CREATE TABLE members
(
member_ID INT NOT NULL,
email VARCHAR(255) NOT NULL,
phone CHAR(10) NOT NULL,
rating VARCHAR(5) NOT NULL,
hashed_password VARCHAR(255) NOT NULL,
member_level INT NOT NULL,
PRIMARY KEY (member_ID),
FOREIGN KEY (member_level) REFERENCES member_level(member_level)
)
MySQL said:
#1215 - Cannot add foreign key constraint
The SQL I'm trying to run is below, I can't figure out what the problem with it is
CREATE TABLE category
(
category_ID INT NOT NULL,
category_name VARCHAR(255) NOT NULL,
PRIMARY KEY (category_ID)
);
CREATE TABLE member_level
(
member_level CHAR(1) NOT NULL,
member_level_description VARCHAR(255) NOT NULL,
PRIMARY KEY (member_level)
);
CREATE TABLE members
(
member_ID INT NOT NULL,
email VARCHAR(255) NOT NULL,
phone CHAR(10) NOT NULL,
rating VARCHAR(5) NOT NULL,
hashed_password VARCHAR(255) NOT NULL,
member_level INT NOT NULL,
PRIMARY KEY (member_ID),
FOREIGN KEY (member_level) REFERENCES member_level(member_level)
);
CREATE TABLE tools
(
tool_ID INT NOT NULL,
serial_number VARCHAR(255) NOT NULL,
tool_name VARCHAR(255) NOT NULL,
tool_description VARCHAR(255) NOT NULL,
tool_picture VARCHAR(255) NOT NULL,
Member_ID INT NOT NULL,
PRIMARY KEY (tool_ID),
FOREIGN KEY (member_ID) REFERENCES members(member_ID)
);
CREATE TABLE tool_category
(
tool_ID INT NOT NULL,
category_ID INT NOT NULL,
FOREIGN KEY (tool_ID) REFERENCES tools(tool_ID),
FOREIGN KEY (category_ID) REFERENCES category(category_ID)
);
-- Populate tables
INSERT INTO member_level VALUES ('a', 'admin');
INSERT INTO member_level VALUES ('m', 'member');
member_level in table members is of type int, while in table member_level is of type CHAR(1).
They must be the same type.

MySQL error:1251 cannot add foreign key

The first 4 table are created fine, the transactions tables run into problem. I get the 1215 error: cannot add foreign key. I've checked an rechecked the data types, and made sure all FK are PK of their own tables. What's wrong here?
CREATE SCHEMA FinalDB;
CREATE TABLE `User` (
userId int not null auto_increment primary key,
first_name varchar(255) not null,
last_name varchar(255) not null,
address varchar(255) null,
DOB date not null,
availableBalance int not null default 0,
currency varchar(20)
);
CREATE TABLE Verifications(
userId int not null primary key,
passport int null,
ssn int null,
license int null,
constraint
foreign key (userId)
references User(userId)
);
CREATE TABLE Linked_Account(
account_Id int not null,
userId int not null,
routing int null,
swift int null,
primary key (userId, account_Id),
constraint
foreign key (userId)
references User(userId)
);
CREATE TABLE Wallet (
userId int not null,
walletId varchar(5) not null,
coinAmount int not null default 0,
netWorth int not null default 0,
primary key(userId, walletId),
constraint
foreign key (userId)
references `User`(userId)
);
CREATE TABLE Transactions (
transactionId int not null primary key auto_increment,
userId int not null,
type varchar(30) not null,
walletId varchar(5) not null,
payment_method int null, #optional
total int null, #optional
quantity int not null,
fee int null, #optional
`date` date not null,
sender varchar(50) null, #optional
reciever varchar(50) null, #optional
status varchar(20) not null,
notes varchar(200) null, #optional
constraint
foreign key (userId)
references `User`(userId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (walletId)
references Wallet(walletId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (payment_method)
references Linked_Account(account_id)
);
CREATE TABLE TransactionsExchange(
transactionId int not null auto_increment primary key,
userId int not null,
currencyFrom int not null,
currencyFromAmount int not null,
currencyInto int not null,
currencyIntoEquivalent int not null,
notes varchar(200) null,
`date` date not null,
constraint
foreign key (userId)
references User(userId),
constraint
foreign key (currencyFrom)
references Wallet(walletId),
constraint
foreign key (currencyInto)
references Wallet(walletId)
);
I've look online for possible answer, but it's usually having to do with inconsistent data types or undeclared PK's. I'm basically trying to make a transactions table to log various different data in different compositions. Using backend logic to handle what is required and what is not, aside from a few defaults.
To use a compound Primary Key as Foreign Key, you'll have to add the
same number of columns (that compose the PK) with same datatypes to
the child table and then use the combination of these columns in the
FOREIGN KEY definition.
see related post here https://stackoverflow.com/a/10566463/4904726
Try this 'Transactions' table creating query:
CREATE TABLE Transactions (
transactionId int not null primary key auto_increment,
userId int not null,
type varchar(30) not null,
walletId varchar(5) not null,
payment_method int null, #optional
total int null, #optional
quantity int not null,
fee int null, #optional
`date` date not null,
sender varchar(50) null, #optional
reciever varchar(50) null, #optional
status varchar(20) not null,
notes varchar(200) null, #optional
constraint
foreign key (userId)
references `User`(userId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (userId, walletId)
references Wallet(userId, walletId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (userId, payment_method)
references Linked_Account(userId, account_id)
);

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

Here is the code below, I'm not sure what this error means...
All I know is that it has something to do with the employeeshifts table.
Does it have something to do with foreign keys?
(insterting this text as I have nothing else to say, but stack requires a lot of text)
CREATE TABLE Customer (
CustomerID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
Phone VARCHAR(45) NULL,
CustomerAddress VARCHAR(45) NOT NULL,
PRIMARY KEY (CustomerID));
CREATE TABLE Location (
Address VARCHAR(100) NOT NULL,
Latitude VARCHAR(45) NULL DEFAULT ' ',
Longitude VARCHAR(45) NULL,
PRIMARY KEY (Address));
CREATE TABLE Employee (
EmployeeID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
PRIMARY KEY (EmployeeID));
CREATE TABLE Truck (
LicensePlate CHAR(20) NOT NULL,
color VARCHAR(45) NULL,
capacity VARCHAR(45) NULL,
PRIMARY KEY (LicensePlate));
CREATE TABLE Shifts (
ShiftTime DATETIME NOT NULL,
PRIMARY KEY (ShiftTime));
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeWorking VARCHAR(90) NOT NULL,
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeWorking, DateOfShift),
FOREIGN KEY (EmployeeWorking) REFERENCES Employee(Name),
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime));
CREATE TABLE Reservation (
ReservNum INT NOT NULL,
ReserveDate DATE 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) NOT NULL,
PassEmployeeHourlyRate DECIMAL (7,2) NOT NULL,
DriverSalary VARCHAR(10),
PassEmployeeSalary VARCHAR(10),
Customer_CustomerID INT,
Truck_LicensePlate char(20) NOT 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));
You need to reference UNIQUE or PRIMARY KEY column:
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeWorking VARCHAR(90) NOT NULL,
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeWorking, DateOfShift),
FOREIGN KEY (EmployeeWorking) REFERENCES Employee(Name), -- name is not UNIQUE/PK
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime)
);
to:
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeID INT NOT NULL, -- here
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeID, DateOfShift),
FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID),
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime)
);
SqlFiddleDemo

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