How to set up Foreign keys MySQL - 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.

Related

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 1064 when creating table. What can I check for?

I'm getting an ERROR 1064 (42000) at line 21, which is VIN_Number in Vehicle table. Entity Inventory gets built without a problem, VIN_Number is of type varchar(17) for all occurrences. I believe the tables are being built in the correct order. I can't find any spelling or punctuation errors. I'm out of ideas of things I should checked. What is it that I'm missing?
Note: I getting an error for Invoice as well, but I know that it can't be created until Vehicle gets created.
ALTER TABLE Vehicle DROP FOREIGN KEY fk_Veh_Vehicle_TypeID;
ALTER TABLE Inventory DROP FOREIGN KEY fk_Inv_Vehicle_TypeID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Customer_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Sales_Person_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_VIN_Number;
DROP TABLE IF EXISTS Vehicle, VehicleType,
Invoice, Customer, SalesPerson, Inventory;
CREATE TABLE VehicleType (
Vehicle_TypeID int NOT NULL,
Veh_Make varchar(15),
Veh_Model varchar(15),
Veh_Year int,
PRIMARY KEY (Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Vehicle (
VIN_Number varchar(17) NOT NULL,
Vehicle_TypeID int NOT NULL,
Condition varchar(10),
Color varchar(8),
PRIMARY KEY (VIN_Number),
CONSTRAINT fk_Veh_Vehicle_TypeID FOREIGN KEY(Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Inventory (
Stock_ID int NOT NULL,
Vehicle_TypeID int NOT NULL,
Quantity int,
PRIMARY KEY (Stock_ID),
CONSTRAINT fk_Inv_Vehicle_TypeID FOREIGN KEY (Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Customer (
Customer_ID varchar(10) NOT NULL,
Cus_LastName varchar(15),
Cus_FirstName varchar(15),
Cus_Street varchar(20),
Cus_City varchar(15),
Cus_Zip varchar(5),
Cus_Phone varchar(10),
PRIMARY KEY (Customer_ID)
) Engine=InnoDB;
CREATE TABLE SalesPerson (
Sales_Person_ID varchar(10) NOT NULL,
Sal_LastName varchar(15),
Sal_FirstName varchar(15),
Sal_Street varchar(15),
Sal_City varchar(15),
Sal_Zip varchar(5),
Sal_Phone varchar(10),
Sal_Years_Worked int,
Sal_Commission_Rate float(4),
PRIMARY KEY (Sales_Person_ID)
) Engine=InnoDB;
CREATE TABLE Invoice (
Invoice_ID varchar(10) NOT NULL,
Customer_ID varchar(10) NOT NULL,
Sales_Person_ID varchar(10) NOT NULL,
VIN_Number varchar(17) NOT NULL,
Price float(10),
PRIMARY KEY (Invoice_ID),
CONSTRAINT fk_Customer_ID FOREIGN KEY (Customer_ID)
REFERENCES Customer(Customer_ID),
CONSTRAINT fk_Sales_Person_ID FOREIGN KEY (Sales_Person_ID)
REFERENCES SalesPerson(Sales_Person_ID),
CONSTRAINT fk_VIN_Number FOREIGN KEY (VIN_Number)
REFERENCES Vehicle(VIN_Number)
) Engine=InnoDB;
In the definition of the Vehicle table you have a column named condition which is a reserved keyword in MySQL (reference). Either use another name for the column or enclose it in backticks like this: `condition`
Using keywords (reserved or not) for object names is generally something you want to avoid.

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

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.

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.