Why do this error appear "#1215 - Cannot add foreign key constraint "? - mysql

CREATE TABLE postcodes (
postcode_ID INT NOT NULL,
location VARCHAR(50),
PRIMARY KEY (postcode_ID)
);
CREATE TABLE countries (
country_ID INT NOT NULL AUTO_INCREMENT,
country_name VARCHAR(50),
PRIMARY KEY (country_ID)
);
CREATE TABLE suppliers (
supplier_ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
supplier_name VARCHAR(50),
supplier_forename VARCHAR(50),
supplier_phonenumber VARCHAR(20),
supplier_address VARCHAR(50),
supplier_postcode INT,
supplier_country INT,
FOREIGN KEY (supplier_postcode) REFERENCES postcode(postcode_ID),
FOREIGN KEY (supplier_country) REFERENCES countries(country_ID)
) ;

Typo:
CREATE TABLE postcodes (
^----plural
FOREIGN KEY (supplier_postcode) REFERENCES postcode(postcode_ID),
^----no S, singular
You're trying to reference a table which doesn't exist.

Related

How to set up Foreign keys MySQL

I am very new to SQL, I am using MySQL running a server set up for me to complete an assignment.
I can't understand what I am doing wrong here when assigning the foreign keys, here is my code
CREATE TABLE Customers (
CustomersID int NOT NULL AUTO_INCREMENT,
CustomerName varchar(50),
AddressLine1 varchar(50),
AddressLine2 varchar(50),
City varchar(50),
State varchar(50),
PostalCode varchar(50),
YTDPurchases decimal(19,2),
PRIMARY KEY (CustomersID)
);
CREATE TABLE TermsCode (
TermsCodeID varchar(50) NOT NULL,
Description varchar(50)
);
CREATE TABLE Invoices (
InvoiceID int NOT NULL AUTO_INCREMENT,
CustomerID int,
InvoiceDate datetime,
TermsCodeID varchar(50),
TotalDue decimal(19,2),
PRIMARY KEY (InvoiceID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomersID),
FOREIGN KEY (TermsCodeID) REFERENCES TermsCode(TermsCodeID)
);
I get this error
MySQL said: Documentation
#1005 - Can't create table table.Invoices` (errno: 150 "Foreign key constraint is incorrectly formed")
You need to add a primary key to the second table, as in:
CREATE TABLE TermsCode (
TermsCodeID varchar(50) NOT NULL,
Description varchar(50),
primary key(TermsCodeID)
);
Once you do that, the tables' creation works well. See example at db<>fiddle.

SQL Fiddle Giving "cannot add foreign key constraint" error

I am trying to figure out what is wrong with my syntax here. I feel like I have matched the examples I have found over the internet... but something must be amiss. Here is the code I am using. I keep getting the error code "cannot add Foreign Key constraint" when trying to run the build the schema.
CREATE TABLE Employe (
employee_id INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
hire_date DATE,
job_title VARCHAR(30),
shop_id INT,
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id)
);
CREATE TABLE Coffee_Shop (
shop_id INT PRIMARY KEY,
shop_name VARCHAR(50),
state CHAR(2),
);
CREATE TABLE Coffee (
coffee_id INT PRIMARY KEY,
shop_id INT,
supplier_id INT,
coffee_name VARCHAR(30),
price_per_pound NUMERIC(5,2),
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id),
FOREIGN KEY (supplier_id) REFERENCES Supplier(supplier_id)
);
CREATE TABLE Supplier (
supplier_id INT PRIMARY KEY,
company_name VARCHAR(50),
country VARCHAR(30),
sales_contact_name VARCHAR(60),
email VARCHAR(50) NOT NULL,
);
I just need to figure out what part of my foreign key is incorrectly defined. I know it normally results from an improperly defined primary key, but cannot seem to find where I messed up.
Thanks for your help
You are referencing a KEY that is not set up yet. SQL is linear, so the code gets executed line-by-line and cannot reference future lines (in most cases)
Create your tables in this order:
CREATE TABLE Coffee_Shop (
shop_id INT PRIMARY KEY,
shop_name VARCHAR(50),
state CHAR(2),
);
CREATE TABLE Supplier (
supplier_id INT PRIMARY KEY,
company_name VARCHAR(50),
country VARCHAR(30),
sales_contact_name VARCHAR(60),
email VARCHAR(50) NOT NULL,
);
CREATE TABLE Employe (
employee_id INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
hire_date DATE,
job_title VARCHAR(30),
shop_id INT,
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id)
);
CREATE TABLE Coffee (
coffee_id INT PRIMARY KEY,
shop_id INT,
supplier_id INT,
coffee_name VARCHAR(30),
price_per_pound NUMERIC(5,2),
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id),
FOREIGN KEY (supplier_id) REFERENCES Supplier(supplier_id)
);

MYSQL 1215 cannot add foreign constraint

So I don't know why i cant add the foreign constraint in the table ORDER_LINE, i made sure all the types are correct. Please help, it keeps on giving me the error
Error Code: 1215. Cannot add foreign key constraint
CREATE TABLE IF NOT EXISTS Customer (
Customer_ID int NOT NULL AUTO_INCREMENT,
Customer_Name VARCHAR(50) NOT NULL,
Customer_Age INT UNIQUE,
Customer_Address VARCHAR(255),
Customer_City VARCHAR(255),
Customer_State VARCHAR(50),
Customer_Zip VARCHAR(20),
PRIMARY KEY(Customer_ID)
);
CREATE TABLE IF NOT EXISTS Sales_order (
Order_ID int AUTO_INCREMENT,
Order_date DATE,
Customer_ID int,
PRIMARY KEY(Order_ID),
FOREIGN KEY(Customer_ID) REFERENCES Customer(Customer_ID) ON DELETE
CASCADE
);
CREATE TABLE IF NOT EXISTS Products (
Product_ID int AUTO_INCREMENT,
Product_Description VARCHAR(255),
Product_Finish VARCHAR(50),
Standard_Price DECIMAL,
Product_Line_ID INT,
PRIMARY KEY(Product_ID)
);
CREATE TABLE IF NOT EXISTS ORDER_LINE (
Order_ID int,
Product_ID int,
Ordered_Quantity int,
PRIMARY KEY(Order_ID, Product_ID),
FOREIGN KEY(Order_ID) REFERENCES Sales_order(Order_ID) ON DELETE SET NULL,
FOREIGN KEY(Product_ID) REFERENCES Products(Product_ID)
);
This might be because primary key columns are made NOT NULL, so your ON DELETE SET NULL is trying to set an invalid value.
EDIT: In fact, I just tested and that does seem to be the issue -- it creates the table if I remove either the SET NULL or the primary key.

MySQL error 1215, what am I doing wrong?

I am trying to create a database that holds staff information such as their names, timesheets, holidays booked etc and also information about the projects the are carrying out and what companies the projects are for. My code is below:
CREATE TABLE IF NOT EXISTS tblcompany (
companyid INT(11) UNSIGNED NOT NULL,
custfirst VARCHAR(50),
custlast VARCHAR(50),
company VARCHAR(50),
custphone VARCHAR(50),
custemail VARCHAR(50),
PRIMARY KEY (companyid),
INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid)
REFERENCES tblproject (companyid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblemployee (
employeeid INT(11) UNSIGNED NOT NULL,
employeefirst VARCHAR(50),
employeelast VARCHAR(50),
employeephone VARCHAR(50),
employeeemail VARCHAR(50),
PRIMARY KEY (employeeid),
INDEX (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tbltimesheet (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblholiday (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblannualleave (employeeid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblholiday (
holidayid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
holidayfrom DATE,
holidayto DATE,
holidayhalfday BOOLEAN,
holidayreason VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (holidayid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblannualleave (
annualleaveid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
annualleavetaken INT(11),
annualleaveremain INT(11),
anuualleavetotal INT(11),
INDEX (employeeid),
PRIMARY KEY (annualleaveid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblproject (
projectid INT(11) UNSIGNED NOT NULL,
projectname VARCHAR(50),
projecttype VARCHAR(50),
companyid INT(11) UNSIGNED NOT NULL,
projectnotes VARCHAR(50),
PRIMARY KEY (projectid),
INDEX (projectid),
CONSTRAINT FOREIGN KEY (projectid)
REFERENCES tbltimesheet (projectid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tbltimesheet (
timesheetid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
projectid INT(11) UNSIGNED NOT NULL,
timesheetdate DATE,
timesheethours INT(11),
timesheetnotes VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (timesheetid)
) ENGINE=InnoDB;
I have been looking around and have tried everything, it is probably something so simple. I have changed all the datatypes to similar ones to see if this would solve the problem butno luck. The error code I get is:
Error Code: 1215. Cannot add foreign key constraint
0.063 sec
CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11) UNSIGNED
NOT NULL, custfirst VARCHAR(50), custlast VARCHAR(50),
company VARCHAR(50), custphone VARCHAR(50), custemail
VARCHAR(50), PRIMARY KEY (companyid), INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid) REFERENCES tblproject
(companyid) ) ENGINE=InnoDB
11:15:57 CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11)
UNSIGNED NOT NULL, custfirst VARCHAR(50), custlast
VARCHAR(50), company VARCHAR(50), custphone VARCHAR(50),
custemail VARCHAR(50), PRIMARY KEY (companyid), INDEX
(companyid), CONSTRAINT FOREIGN KEY (companyid) REFERENCES
tblproject (companyid) ) ENGINE=InnoDB Error Code: 1215. Cannot add
foreign key constraint 0.063 sec
Thank you for looking..
Create the table tblproject first before you reference it.
Besides the wrong table order,you need either a primary or unique key on referenced columns.
SQL fiddle
I think you will solve your problem creating your tables in the opposite ordersm, otherwise you will have the same issue with tblemployee.
A Foreigh Key needs that the reference table exists already.
You cannot create a foreign key when the table it references does not yet exist. You can always create the foreign key later.
You must first create the tables containing the referenced fields, after you create the table with the foreign key.
You could also create first all the tables, and create all foreign keys in a second step.

Unable To Create Table, Unsure of what to do (Error: 150)

I am creating several tables at once and I keep getting the error(150):
#1005 - Can't create table 'waget.tour' (errno: 150)
and despite me knowing what the error is, I simply can't fix it. All tables references in the table "tour" are all there and exist, with keys where Foreign keys are referenced. I've checked it over plenty of times, and simply can't find anything. Can anyone see what I am doing wrong?
(Getting error when creating the table "tours")
CREATE TABLE IF NOT EXISTS tourPayment(
tourPaymentNumber int,
tourCost int(7),
PRIMARY KEY (tourPaymentNumber),
KEY (tourCost)
);
CREATE TABLE IF NOT EXISTS hotel(
hotelID int AUTO_INCREMENT,
hotelName varchar(30),
PRIMARY KEY (hotelID),
KEY (hotelName)
);
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutation)
);
CREATE TABLE IF NOT EXISTS customer(
custID int AUTO_INCREMENT,
custSalutation varchar(4),
custLname varchar(30),
custAdd varchar(100),
custPcode varchar(4),
custState varChar(20),
custPhone varchar(10),
custHotel varchar(30),
PRIMARY KEY (custID),
FOREIGN KEY (custHotel) REFERENCES hotel(hotelName),
FOREIGN KEY (custSalutation) REFERENCES salutation(salutation)
);
CREATE TABLE IF NOT EXISTS bus(
busID int AUTO_INCREMENT,
busMake varchar(30),
busSeats varchar(3),
PRIMARY KEY (busID)
);
CREATE TABLE IF NOT EXISTS busDriver(
driverID int AUTO_INCREMENT,
driverName varchar(20),
driverEmail varchar(40),
busID int,
PRIMARY KEY (driverID),
FOREIGN KEY (busID) REFERENCES bus(busID)
);
CREATE TABLE IF NOT EXISTS tour(
DailyTourID int AUTO_INCREMENT,
NoOfPeople int(3),
tourDate DATE,
tourTime TIME,
tourName varchar(30),
tourCost int(7),
tourDriverID varchar(20),
PRIMARY KEY (DailyTourID),
FOREIGN KEY (tourDriverID) REFERENCES busDriver(driverID),
FOREIGN KEY (tourCost) REFERENCES tourPayment(tourCost)
);
CREATE TABLE IF NOT EXISTS TourCustLink(
TourCustLinkID int AUTO_INCREMENT,
TourID int,
custID int,
PRIMARY KEY (TourCustLinkID),
FOREIGN KEY (TourID) REFERENCES tour(DailyTourID),
FOREIGN KEY (custID) REFERENCES customer(custID)
);
Here is your problem:
FOREIGN KEY (tourDriverID) REFERENCES busDriver(driverID)
references an INT but is declared as varchar(20)
AUTO_INCREMENT fields all need to be PRIMARY KEY's, so try changing salutation to be
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
PRIMARY KEY (salutationID),
KEY (salutation)
);
Additionally in tour you have the wrong datatype for tourDriverID, it should be INT to match the referenced key
CREATE TABLE IF NOT EXISTS tour(
DailyTourID int AUTO_INCREMENT,
NoOfPeople int(3),
tourDate DATE,
tourTime TIME,
tourName varchar(30),
tourCost int(7),
tourDriverID INT,
PRIMARY KEY (DailyTourID),
FOREIGN KEY (tourDriverID) REFERENCES busDriver(driverID),
FOREIGN KEY (tourCost) REFERENCES tourPayment(tourCost)
);
SQL fiddle example in full can be found here : http://sqlfiddle.com/#!2/840b9
Actually it's easy to try and create tables one by one and you would get a better error message..
Your Problem is the table salutation since you have to define the AUTO_INCREMENT field (in your case salutationID) as KEY and not the fieldsalutation`
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutationID) -- here is your error
);
Is this the code you ran? if so, the error is about the AUTO_INCREMENT needing to be a Key.
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutation)
);
Try:
CREATE TABLE IF NOT EXISTS salutation(
salutationID int AUTO_INCREMENT,
salutation varchar(4),
KEY (salutationID)
);
and make other a FOREIGN KEY if you need to.
Cheers.