Mysql foreign key constraint is incorrectly formed? - mysql

I am receiving an error when attempting to create some tables in mysql with the foreign key
CREATE TABLE session (
code CHAR(2) NOT NULL,
date DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (date),
CONSTRAINT session_fk FOREIGN KEY (code)
REFERENCES module(code));
CREATE TABLE module (
code CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (code));
Here are the two tables I am trying to create, the syntax I've used matches w3 schools and both data types are the same so I cannot see how this is incorrect, any help would be appreciated thanks :)

You're trying to create a foreign key on table before creating the referencing table.
Interchanging the order of query will work :
CREATE TABLE module (
`code` CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (`code`));
CREATE TABLE `session` (
`code` CHAR(2) NOT NULL,
`date` DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (`date`),
CONSTRAINT session_fk FOREIGN KEY (`code`)
REFERENCES module(`code`));

Try this
CREATE TABLE module (
code CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (code));
CREATE TABLE session (
code CHAR(2) NOT NULL,
date DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (date),
CONSTRAINT session_fk FOREIGN KEY (code)
REFERENCES module(code));

Related

I am getting an Error 1822 failed when trying to create MySQL tables

When I try and run this query, I get an error:
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint.
However, based on other posts, I have ensured the data types were matching. Can someone please help me out? The issue is with the last table.
CREATE TABLE Client
(
client_id int NOT NULL,
client_name varchar(50) NOT NULL,
client_address varchar(50) NOT NULL,
client_city varchar(10) NOT NULL,
client_prov varchar(2) NOT NULL,
client_postal varchar(6) NOT NULL,
PRIMARY KEY (client_id),
UNIQUE (client_name)
);
CREATE TABLE Programmer
(
prog_id decimal(5,0),
prog_name varchar(30) NOT NULL,
prog_office char(5) NOT NULL,
prog_phone char(10) NOT NULL,
PRIMARY KEY (prog_id)
);
CREATE TABLE Project
(
project_id decimal(6,1),
project_name varchar(40) NOT NULL,
complete_date date ,
total_cost decimal(7,2) NOT NULL,
client_id int NOT NULL,
UNIQUE (project_name),
FOREIGN KEY (client_id) REFERENCES Client (client_id),
CHECK (complete_date > "2020-01-01"),
CHECK(total_cost > 0)
);
CREATE TABLE Project_mm_Programmer
(
prog_id decimal(5,0),
project_id decimal(6,1),
hours_worked decimal(3,1), -- NOT NULL,
FOREIGN KEY (prog_id) REFERENCES Programmer (prog_id) ,
FOREIGN KEY (project_id) REFERENCES Project (project_id),
CHECK(hours_worked > 0)
);
The Issue is on the creation of the last table. It references a PK for the bridging table. The foreign key uses Project ID PK but..
Your table Project doesn't have a primary key like the Programmer and Client Tables do
CREATE TABLE Client (
client_id int NOT NULL,
client_name varchar(50) NOT NULL,
client_address varchar(50) NOT NULL,
client_city varchar(10) NOT NULL,
client_prov varchar(2) NOT NULL,
client_postal varchar(6) NOT NULL,
primary key (client_id),
unique (client_name)
);
CREATE TABLE Programmer (
prog_id decimal(5,0),
prog_name varchar(30) NOT NULL,
prog_office char(5) NOT NULL,
prog_phone char(10) NOT NULL,
primary key (prog_id)
);
CREATE TABLE Project (
project_id decimal(6,1),
project_name varchar(40) NOT NULL,
complete_date datetime,
total_cost decimal(7,2) NOT NULL,
client_id int NOT NULL,
unique (project_name),
FOREIGN KEY (client_id) REFERENCES Client (client_id),
CHECK (complete_date > '2020-01-01'), -- may have to change back to double ticks
CHECK(total_cost>0),
primary key (project_id) -- add this line for sure
);
CREATE TABLE Project_mm_Programmer (
prog_id decimal(5,0),
project_id decimal(6,1),
hours_worked decimal(3,1), -- NOT NULL,
FOREIGN KEY (prog_id) REFERENCES Programmer (prog_id) ,
FOREIGN KEY (project_id) REFERENCES Project (project_id),
CHECK(hours_worked>0)
);

Error code:1215 Cannot add foreign key constraint while running script in MySQL workbench version 6.3

First of all i apologize that the names of the tables and so on are in another language.
The issue is i can't seem to add a foreign key named ID_KOPIE from the table KOPIA_KNIHY into the table SKLAD for some reason. When it gets to adding the foreign key to to the table SKLAD it throws out an error 1215. Here is the code:
CREATE TABLE BOOK (
BOOK_NAME VARCHAR(30) NOT NULL,
YEAR CHAR(4) NOT NULL,
NAME_OF_EDITOR VARCHAR(30) NOT NULL,
WRITER_ID INTEGER NOT NULL,
ISBN VARCHAR(17) NOT NULL,
BOOK_ID INTEGER NOT NULL,
PRIMARY KEY (BOOK_ID),
);
CREATE TABLE BOOK_COPY(
BOOK_ID INTEGER NOT NULL,
LANGUAGE_CODE CHAR(3) NOT NULL,
COPY_ID INTEGER NOT NULL,
BOOK_PICTURES CHAR(1) NOT NULL
CHECK (BOOK_PICTURES IN ("Y", "N")),
PRIMARY KEY (BOOK_ID, LANGUAGE_CODE, COPY_ID)
FOREIGN KEY(BOOK_ID)
REFERENCES BOOK(BOOK_ID),
);
CREATE TABLE STORAGE (
BOOK_ID INTEGER NOT NULL,
COPY_ID INTEGER NOT NULL,
BUILDING_ID INTEGER NOT NULL,
ROOM_NUMBER NUMERIC(4,0) NOT NULL,
SHELF_NUMBER NUMERIC(4,0) NOT NULL,
PRIMARY KEY(BOOK_ID, BUILDING_ID, COPY_ID),
FOREIGN KEY(COPY_ID)
REFERENCES BOOK_COPY(BOOK_ID),
)
I researched the error code 1215 on the internet, i couldn't find anything wrong with my database. I checked if there's a typo or if i didn't forget to add the reference.
This is the error:
0 769 18:19:37 CREATE TABLE STORAGE (
BOOK_ID INTEGER NOT NULL,
COPY_ID INTEGER NOT NULL,
BUILDING_ID INTEGER NOT NULL,
ROOM_NUMBER NUMERIC(4,0) NOT NULL,
SHELF_NUMBER NUMERIC(4,0) NOT NULL,
PRIMARY KEY(BOOK_ID, BUILDING_ID, COPY_ID),
FOREIGN KEY(COPY_ID)
REFERENCES BOOK_COPY(BOOK_ID),
)
Error Code: 1215. Cannot add foreign key constraint 0.016 sec
My question is how can this be fixed that it would work.
Help would be greatly appreciated.
Try this way. Please do alter the ON UPDATE ... ON DELETE syntax in this example with the one you need.
CREATE TABLE `KNIHA` (
`NAZOV_KNIHY` VARCHAR(30) NOT NULL,
`ROK_PRVEHO_VYDANIA` CHAR(4) NOT NULL,
`NAZOV_VYDAVATELA` VARCHAR(30) NOT NULL,
`ID_AUTORA` INTEGER NOT NULL,
`ISBN` VARCHAR(17) NOT NULL,
`ID_KNIHY` INTEGER NOT NULL,
PRIMARY KEY (`ID_KNIHY`)
);
CREATE TABLE `KOPIA_KNIHY` (
`ID_KNIHY` INTEGER NOT NULL,
`KOD_JAZYKA` CHAR(3) NOT NULL,
`ID_KOPIE` INTEGER NOT NULL,
`ORAZKY_V_KNIHE` CHAR(1) NOT NULL
CHECK (`OBRAZKY_V_KNIHE` IN ("A", "N")),
INDEX(`ID_KOPIE`),
PRIMARY KEY (`ID_KNIHY`, `KOD_JAZYKA`, `ID_KOPIE`),
CONSTRAINT `idx_1` FOREIGN KEY `idx_1` (`ID_KNIHY`) REFERENCES `KNIHA`(`ID_KNIHY`) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE `SKLAD` (
`ID_KNIHY` INTEGER NOT NULL,
`ID_KOPIE` INTEGER NOT NULL,
`ID_BUDOVY` INTEGER NOT NULL,
`CISLO_MIESTNOSTI` NUMERIC(4,0) NOT NULL,
`CISLO_REGALU` NUMERIC(4,0) NOT NULL,
PRIMARY KEY(`ID_KNIHY`, `ID_BUDOVY`, `ID_KOPIE`),
CONSTRAINT `idx_2` FOREIGN KEY `idx_2` (`ID_KOPIE`) REFERENCES `KOPIA_KNIHY`(`ID_KOPIE`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `idx_3` FOREIGN KEY `idx_3` (`ID_KNIHY`) REFERENCES `KNIHA`(`ID_KNIHY`) ON UPDATE CASCADE ON DELETE CASCADE
);
Try it on SQL Fiddle
.

#1072 - Key column 'Customer_ID' doesn't exist in table

This is the parent table
CREATE TABLE Customer(
Customer_ID INT(5) not null,
CustName VARCHAR(50) not null,
CustSurname VARCHAR(50) not null,
CustEmail VARCHAR(100) unique not null,
CustMobileNo INT(12) not null,
HomeAddress VARCHAR(255) not null,
Password VARCHAR(10) not null,
constraint c_cuid_pk PRIMARY KEY (Customer_ID))
ENGINE = InnoDB;
When I try to create the property table it shows me
"#1072 - Key column 'Customer_ID' doesn't exist in table"
this is the child table
CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;
In table Property, you must define a column named Customer_ID (well it could be named anything!), then you define the FOREIGN KEY on it.
Your code currently tries to link IndificualCustomer(Customer_ID) to Property(Customer_ID), but Property(Customer_ID) does not exist.
Declaring the constraint just links the columns, but it does not create them.
CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
Customer_ID INT(5) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;
In the first place, you should add a column: Customer_ID to your Property table to create your foreign key constraint:
Property.Customer_ID → IndividualCustomer.Customer_ID
You can not make a constraint on something that does not exist.
Or change the +++ +++ part of your table creation query to a column that exists.
constraint p_cuid_fk FOREIGN KEY (+++Customer_ID+++) --to be changed accordingly
references IndividualCustomer(Customer_ID)
Example: adding the Customer_ID column to your table declaration would give you the following code
CREATE TABLE Property(
Property_ID INT(5) not null,
Customer_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;
CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
Customer_ID INT(5) not null,
PRIMARY KEY (Property_ID),
KEY p_cuid_fk (Customer_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references Customer(Customer_ID))
ENGINE = InnoDB;
You have to add Customer_ID in the table PROPERTY.

MySQL Workbench won't allow me to create foreign keys

I'm trying to create a few tables and one of them has should have foreign keys referencing the other tables, but MySQL Workbench keeps giving me "Error Code: 1215. Cannot add foreign key constraint". This happens if I try to create them during the table creation and if I just create the table and then try to add FK through ALTER. I just can't figure out the problem. I've tried both with and without ENGINE = InnoDB that I saw some people suggest on the web. And yes, tables kommune and person has been created.
CREATE TABLE kommune (
Kommunenr varchar(4) NOT NULL,
Kommunenavn varchar(45) NOT NULL,
PRIMARY KEY (Kommunenr));
CREATE TABLE person (
PersonID varchar(4) NOT NULL,
Fornavn varchar(45) NOT NULL,
Etternavn varchar(45) NOT NULL,
Postnr varchar(4) NOT NULL,
Poststed varchar(45) NOT NULL,
PRIMARY KEY (PersonID));
CREATE TABLE oppdrag (
Oppdragsnr varchar(5) NOT NULL,
Eiendomnr varchar(4) NOT NULL,
Gateadresse varchar(45) NOT NULL,
Postnr varchar(4) NOT NULL,
Poststed varchar(45) NOT NULL,
Kommunenr varchar(4) NOT NULL,
Prisantydning varchar(10) NOT NULL,
Solgt boolean NOT NULL,
PRIMARY KEY (Oppdragsnr),
FOREIGN KEY (Postnr) REFERENCES person(Postnr),
FOREIGN KEY (Poststed) REFERENCES person(Poststed),
FOREIGN KEY (Kommunenr) REFERENCES kommune(Kommunenr));
Check the following lines:
FOREIGN KEY (Postnr) REFERENCES person(Postnr),
FOREIGN KEY (Poststed) REFERENCES person(Poststed),
but in your table structure:
CREATE TABLE person (
PersonID varchar(4) NOT NULL,
Fornavn varchar(45) NOT NULL,
Etternavn varchar(45) NOT NULL,
Postnr varchar(4) NOT NULL,
Poststed varchar(45) NOT NULL,
PRIMARY KEY (PersonID));
Postnr, Poststed are neither unique or not primary key. To make foreign key, the referring column in the base table must be an indexed column

#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