MySQL #1215 Issue - mysql

I keep getting an issue with creating this table in my database. The issue is:
Error:1215 Cannot add foreign key constraint.
This is the table I am trying to make:
CREATE TABLE Customer (
customer_reference int UNIQUE AUTO_INCREMENT,
primary key (customer_reference),
forename VARCHAR(20),
surname VARCHAR(20),
contact VARCHAR(15),
email VARCHAR(50),
building VARCHAR(5),
road VARCHAR(40),
city VARCHAR(30),
postcode VARCHAR(7),
county VARCHAR(30));
CREATE TABLE Invoice (
invoice_reference int UNIQUE AUTO_INCREMENT,
customer_reference int UNIQUE,
primary key (invoice_reference),
foreign key (customer_reference) references Customer(customer_reference),
invoice_cost DECIMAL(20,2),
paid bit,
order_date DATETIME,
delivery_date DATE);
CREATE TABLE Stock (
container VARCHAR(10) UNIQUE NOT NULL DEFAULT 0,
primary key (container),
SBADNLon INT(4),
SBADNFel INT(4),
SBADNSou INT(4),
CHECK (container = ("SBADN-Lon" > 0, "SBADN-Fel" > 0, "SBADN-Sou" > 0)));
/* This is just showing 3 of the possible container variations
Each attribute stores a value containing the number of that model available in inventory
*/
CREATE TABLE Items_Purchased (
container_ordered VARCHAR(10) NOT NULL,
invoice_reference int,
container VARCHAR(10) NOT NULL DEFAULT "None",
container_cost decimal(20,2) NULL,
container_size VARCHAR(6) NOT NULL,
colour VARCHAR(5) NOT NULL,
grade CHAR(1) NOT NULL,
depot VARCHAR(15) NOT NULL,
container_type VARCHAR(20) NOT NULL,
conditionn VARCHAR(4) NOT NULL,
primary key (container_ordered, container_size, colour, grade, depot, container_type, conditionn),
foreign key (invoice_reference) references Invoice (invoice_reference),
foreign key (container) references Stock (container),
foreign key (container_size) references Container_Size (container_size),
foreign key (colour) references Colour (colour),
foreign key (grade) references Grade (grade),
foreign key (depot) references Depot (depot),
foreign key (container_type) references Container_Type (container_type),
foreign key (conditionn) references Conditionn (conditionn));
CREATE TABLE Depot (
depot VARCHAR(15) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (depot),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (depot = ("london","felixstowe","southampton")));
CREATE TABLE Container_Type (
container_type VARCHAR(20) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (container_type),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_type = ("dry","inslated","refreigerated","open top","tunnel")));
CREATE TABLE Container_Size (
container_size VARCHAR(6) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (container_size),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_size = ("small","medium","large")));
CREATE TABLE Colour (
colour VARCHAR(5) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (colour),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (colour = ("black","green")));
CREATE TABLE Conditionn (
conditionn VARCHAR(4) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (conditionn),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (conditionn = ("new","used")));
CREATE TABLE Grade (
grade CHAR(1) NOT NULL,
container_ordered VARCHAR(10) NOT NULL,
primary key (grade),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (grade = ("a","b","c")));
Thanks in advance

First of all, I believe it would be better to use another primary key for your table.
The datatypes of all the foreign key constraints should be exactly the same as how the fields are defined as primary keys in the original table. If container is varchar(20) in Stock table, for example, it has to be varchar(20) in Items_Purchased table.
Also, the collations defined (if any) would be the same, like utf-8 for those columns. Note that your tables might be in the same collaction, but the columns might have different, check properly.
Lastly, make sure the values for the foreign key values are unique and the definition of foreign key columns include not null
Reference: MySQL Error 1215: Cannot add foreign key constraint

the following 2 rules might have caused the error:
invoice_reference int UNIQUE auto_increment
foreign key (invoice_reference) references Invoice (invoice_reference)
The auto_increment property should be specified in the Invoice table (invoice_reference) instead.

I tried inserting each foreign key definition separately using the ALTER table command and it took it well - maybe some form of referencing issue?

My guess is, See in order to create a foreign key reference, the referenced table must be created before its reference is created. For example, check your third table. It contains a customer reference and it is working fine.
Now if you see DEPOT table and Items_Purchased table, both contains foreign key references on each other. Now think about it, In order to reference from Depot to Items_Purchased, Items_purchased must be present before Depot, and the vice versa must be true as well for referencing Items_Purchased to Depot. This will never be possible.
Please reconstruct your schema accordingly, and sort out which table should be created first, in order to get reference from that table.
This is more like a forward referencing error you face while compiling code in Java.

Related

How to solve the errno: 150 "Foreign key constraint is incorrectly formed" even though my constraint is correct?

I am trying to create three tables :
Hotel Table
CREATE TABLE Hotels(
HotelID VARCHAR(30) NOT NULL,
Name VARCHAR(30) NOT NULL,
City VARCHAR(30) NOT NULL,
Rating VARCHAR(30) NOT NULL,
Description VARCHAR(500) NOT NULL,
PRIMARY KEY (HotelID)
)
Rooms table
CREATE TABLE Rooms (
HotelID VARCHAR(30) NOT NULL,
Room_Number INT NOT NULL,
Price_Rate INT NOT NULL,
Type VARCHAR(30) NOT NULL,
PRIMARY KEY(HotelID, Room_Number),
FOREIGN KEY(HotelID) REFERENCES hotels(HotelID)
)
BookingInfo Table
CREATE TABLE BookingInfo (
HotelID VARCHAR(30) NOT NULL,
UserID VARCHAR(30) NOT NULL,
Room_Number INT NOT NULL,
Arrival_Date DATE NOT NULL,
Departure_Date DATE NOT NULL,
PRIMARY KEY(UserID, HotelID, Room_Number, Arrival_Date),
FOREIGN KEY(HotelID) REFERENCES hotels(HotelID),
FOREIGN KEY(UserID) REFERENCES users(UserID),
FOREIGN KEY (Room_Number) REFERENCES rooms(Room_Number)
)
But when I try to create the third table I am getting errno: 150 "Foreign key constraint is incorrectly formed".
Moreover, when I delete FOREIGN KEY (Room_Number) REFERENCES rooms(Room_Number) the table gets created successfully. But I don't understand why it is not accepting FOREIGN KEY (Room_Number) REFERENCES rooms(Room_Number).
I have also tried to alter the table and change data type but still didn't get any success. Can anyone please point out my the mistake in this codes.
The primary key of Rooms is two columns: (HotelID, Room_Number).
The foreign key in BookingInfo is one column: (Room_Number).
A foreign key should reference the whole primary key of the referenced table. If that primary key has more than one column, all of the columns must be referenced by the foreign key, and in the same order.
Caveat that is not standard SQL and specific to InnoDB: InnoDB allows a foreign key to reference part of a multi-column key in the referenced table, as long as the column is the leftmost column of that key. But in your case, you are referencing the second from the left column of that key, Room_Number. So it's not allowed. And in my opinion, it's a bad idea anyway to reference part of the key, because it leads to weird data anomalies.
REFERENCES rooms(Room_Number) room_number has to be a key or the first node of a multi column key
'In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order.' https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
Thanks a lot for the guidance. This code has worked for me :
CREATE TABLE BookingInfo (
HotelID VARCHAR(30) NOT NULL,
UserID VARCHAR(30) NOT NULL,
Room_Number INT NOT NULL,
Arrival_Date DATE NOT NULL,
Departure_Date DATE NOT NULL,
PRIMARY KEY(UserID, HotelID, Room_Number, Arrival_Date),
FOREIGN KEY(UserID) REFERENCES users(UserID),
FOREIGN KEY(HotelID,Room_Number) REFERENCES rooms(HotelID,Room_Number)
)

MySQL Error: 1452 - Cannot add or update a child row

Error seems to occur when I try to INSERT into Items_Puchased (bottom lines). Ignore all comments.
Error Code: 1452. Cannot add or update a child row: a foreign key
constraint fails (shippingcontainers.items_purchased, CONSTRAINT
items_purchased_ibfk_2 FOREIGN KEY (container) REFERENCES stock
(container))
CREATE TABLE Customer (
customer_reference int UNIQUE AUTO_INCREMENT,
primary key (customer_reference),
forename VARCHAR(20),
surname VARCHAR(20),
contact VARCHAR(15),
email VARCHAR(50),
building VARCHAR(5),
road VARCHAR(40),
city VARCHAR(30),
postcode VARCHAR(7),
county VARCHAR(30));
CREATE TABLE Invoice (
invoice_reference int UNIQUE AUTO_INCREMENT,
customer_reference int UNIQUE,
primary key (invoice_reference),
foreign key (customer_reference) references Customer(customer_reference),
invoice_cost DECIMAL(20,2),
paid bit,
order_date DATETIME,
delivery_date DATE);
CREATE TABLE Stock (
container VARCHAR(10) UNIQUE NOT NULL DEFAULT 0,
primary key (container),
SBADNLon INT(4),
SBADNFel INT(4),
SBADNSou INT(4),
CHECK (container = ("SBADN-Lon" > 0, "SBADN-Fel" > 0, "SBADN-Sou" > 0)));
This is just showing 3 of the possible container variations
Each attribute stores a value containing the number of that model available in inventory
CREATE TABLE Items_Purchased (
container_ordered int UNIQUE AUTO_INCREMENT,
invoice_reference int,
container VARCHAR(10) NOT NULL DEFAULT "None",
container_cost decimal(20,2) NULL,
container_size VARCHAR(6) NOT NULL,
colour VARCHAR(5) NOT NULL,
grade CHAR(1) NOT NULL,
depot VARCHAR(15) NOT NULL,
container_type VARCHAR(20) NOT NULL,
conditionn VARCHAR(4) NOT NULL,
primary key (container_ordered, container_size, colour, grade, depot, container_type, conditionn));
foreign key (invoice_reference) references Invoice (invoice_reference),
foreign key (container) references Stock (container),
foreign key (container_size) references Container_Size (container_size),
foreign key (colour) references Colour (colour),
foreign key (grade) references Grade (grade),
foreign key (depot) references Depot (depot),
foreign key (container_type) references Container_Type (container_type),
foreign key (conditionn) references Conditionn (conditionn));
CREATE TABLE Depot (
depot VARCHAR(15) NOT NULL,
container_ordered int,
primary key (depot),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (depot = ("london","felixstowe","southampton")));
CREATE TABLE Container_Type (
container_type VARCHAR(20) NOT NULL,
container_ordered int,
primary key (container_type),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_type = ("dry","inslated","refreigerated","open top","tunnel")));
CREATE TABLE Container_Size (
container_size VARCHAR(6) NOT NULL,
container_ordered int,
primary key (container_size),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (container_size = ("small","medium","large")));
CREATE TABLE Colour (
colour VARCHAR(5) NOT NULL,
container_ordered int,
primary key (colour),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (colour = ("black","green")));
CREATE TABLE Conditionn (
conditionn VARCHAR(4) NOT NULL,
container_ordered int,
primary key (conditionn),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (conditionn = ("new","used")));
CREATE TABLE Grade (
grade CHAR(1) NOT NULL,
container_ordered int,
primary key (grade),
foreign key (container_ordered) references Items_Purchased(container_ordered),
CHECK (grade = ("a","b","c")));
I am unsure on why I am getting this error code, can anyone assist? It occurs when adding
INSERT INTO Customer (
forename, surname, contact, email, building, road, city, postcode, county)
VALUES (
"james", "kelly", 07930317616, "james#uni.com", 123, "Yellow Road", "Ipswich", "IP11SQ", "Suffolk");
INSERT INTO Customer (
forename, surname, contact, email, building, road, city, postcode, county)
VALUES (
"ben", "smith", 0793031754, "ben#uni.com", 45, "Red Road", "Woodbridge", "IP142DD", "Suffolk");
INSERT INTO Invoice (
invoice_cost, paid, order_date, delivery_date)
VALUES (
1435.34, 1, 19/12/2017, 21/12/2017);
INSERT INTO Invoice (
invoice_cost, paid, order_date, delivery_date)
VALUES (
1035.12, 0, 02/02/2018, 29/12/2017);
INSERT INTO Stock (
SBADNLon, SBADNFel, SBADNSou)
VALUES (
3, 2, 1);
INSERT INTO Items_Purchased (
container_cost, container_size, colour, grade, depot, container_type, conditionn)
VALUES (
1645.21, "large", "black", "a", "london", "insulated", "new")
Look at your foreign key relationships with the Items_Purchased table. It sounds like you have a mismatch happening. And in looking at your table definition, you have a lot of foreign keys identified. This type of spider web construction is not typical and can cause you many problems. I would also take another look at your foreign keys and assess what the need is for each of them.
Your default value in table stock for column container is 0 and the default value for that column in the Items_Purchased table is "None".
As you don't assign any value for those columns in your insert statements, when you try to insert into the Items_Purchased table, it uses the default value for the column container "None" and this value doesn't exist in your stock table (the only value that exists it's 0).
You should make them the same value, or as default, in your Items_Purchased table set it as 0 like:
CREATE TABLE Items_Purchased (
container_ordered int UNIQUE AUTO_INCREMENT,
invoice_reference int,
container VARCHAR(10) NOT NULL DEFAULT 0,
container_cost decimal(20,2) NULL,
container_size VARCHAR(6) NOT NULL,
colour VARCHAR(5) NOT NULL,
grade CHAR(1) NOT NULL,
depot VARCHAR(15) NOT NULL,
container_type VARCHAR(20) NOT NULL,
conditionn VARCHAR(4) NOT NULL,
primary key (container_ordered, container_size, colour, grade, depot, container_type, conditionn));
foreign key (invoice_reference) references Invoice (invoice_reference),
foreign key (container) references Stock (container),
foreign key (container_size) references Container_Size (container_size),
foreign key (colour) references Colour (colour),
foreign key (grade) references Grade (grade),
foreign key (depot) references Depot (depot),
foreign key (container_type) references Container_Type (container_type),
foreign key (conditionn) references Conditionn (conditionn));

Can not Add External Index Constraints

This is the exact error that WAMP returns when I run the child code from an external file called entries.txt
ERROR 1215 (HY000): Can not Add External Index Constraints
I need to be able to connect the parent tables to the child table so that links can be made between the tables easily.
The question states:
Create and populate a third table called entries, again using query scripts.
This table should contain foreign keys to allow sensible links to be
made with the other two tables, together with the dates of each exam.
Parent Tables:
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id),
UNIQUE (email));
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name CHAR(30) NOT NULL,
level_of_entry VARCHAR(10) NOT NULL,
exam_board CHAR(20) NOT NULL,
PRIMARY KEY (subject_id));
Child Table:
CREATE TABLE IF NOT EXISTS entries(
date_of_exam DATETIME NOT NULL,
first_name VARCHAR,
middle_name VARCHAR,
last_name VARCHAR,
subject_name CHAR,
level_of_entry VARCHAR,
exam_board CHAR,
INDEX idx_first_name(first_name),
INDEX idx_middle_name(middle_name),
INDEX idx_last_name(last_name),
INDEX idx_subject_name(subject_name),
INDEX idx_level_of_entry(level_of_entry),
INDEX idx_exam_board(exam_board),
PRIMARY KEY (date_of_exam),
CONSTRAINT fk_first_name FOREIGN KEY (first_name) REFERENCES students(first_name),
CONSTRAINT fk_middle_name FOREIGN KEY (middle_name) REFERENCES students(middle_name),
CONSTRAINT fk_last_name FOREIGN KEY (last_name) REFERENCES students(last_name),
CONSTRAINT fk_subject_name FOREIGN KEY (subject_name) REFERENCES subjects(subject_name),
CONSTRAINT fk_level_of_entry FOREIGN KEY (level_of_entry) REFERENCES subjects(level_of_entry),
CONSTRAINT fk_exam_board FOREIGN KEY (exam_board) REFERENCES subjects(exam_board)
)ENGINE=InnoDB;
A foreign key in the child table must reference the primary key of the parent table only. You don't need to create clones of every attribute column of the parent tables, just the primary key column. If you need to read the other attributes, you'd write a query with a JOIN.
CREATE TABLE IF NOT EXISTS entries(
student_id INT UNSIGNED NOT NULL,
subject_id INT UNSIGNED NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (student_id, subject_id, date_of_exam),
CONSTRAINT fk_student FOREIGN KEY (student_id) REFERENCES students(student_id),
CONSTRAINT fk_subject FOREIGN KEY (subject_id) REFERENCES subjects(subject_id),
)ENGINE=InnoDB;

MySQL error: cannot add foreign key constraint, but data types match

I'm trying to create tables with foreign keys, but I keep getting error 1215 saying that it cannot add foreign key constraint. I double checked the datatypes and the REFERENCES part of the constraint, and that seems to be in order. I added ENGINE=InnoDB after reading through some of the MySQL documentation for the error, and that didn't solve it. I'm new to creating new databases, so I think I'm missing something. What can I add to resolve this error?
CREATE DATABASE cemc;
USE cemc;
CREATE TABLE CALENDAR(
year INT NOT NULL,
term VARCHAR(25) NOT NULL,
term_start DATE NOT NULL,
term_end date NOT NULL,
CONSTRAINT CALENDAR_PK PRIMARY KEY(year, term)
)ENGINE=InnoDB;
CREATE TABLE COURSE(
course_id VARCHAR(6) NOT NULL,
skill VARCHAR(25) NOT NULL,
level VARCHAR(25) NOT NULL,
CONSTRAINT COURSE_PK PRIMARY KEY(course_id)
)ENGINE=InnoDB;
CREATE TABLE TEACHER(
teacher_id VARCHAR(50) NOT NULL,
teacher_last VARCHAR(25) NOT NULL,
teacher_first VARCHAR(25) NOT NULL,
email1 VARCHAR(50) NOT NULL,
email2 VARCHAR(50) NULL,
phone1 INT NOT NULL,
phone2 INT NULL,
CONSTRAINT TEACHER_PK PRIMARY KEY(teacher_id)
)ENGINE=InnoDB;
CREATE TABLE COURSEASSIGNMENT(
course_id VARCHAR(6) NOT NULL,
year INT NOT NULL,
term VARCHAR(25) NOT NULL,
teacher_id VARCHAR(50) NULL,
room VARCHAR(3) NULL,
CONSTRAINT COURSEA_PK PRIMARY KEY(course_id, term),
CONSTRAINT COURSEA_FK1 FOREIGN KEY(term)
REFERENCES CALENDAR(term),
CONSTRAINT COURSEA_FK2 FOREIGN KEY(course_id)
REFERENCES COURSE(course_id),
CONSTRAINT COURSEA_FK3 FOREIGN KEY(year)
REFERENCES CALENDAR(year),
CONSTRAINT COURSEA_FK4 FOREIGN KEY(teacher_id)
REFERENCES TEACHER(teacher_id)
)ENGINE=InnoDB;
The problem is that you try to reference Calendar. So far you are doing it correct with the data types. BUT Calendar has a combined primary key. Thus you need to define the foreign key in one go instead of both separated, as mysql interprets these 2 as SEPARATE foreign keys instead of a combined one. And that leads to it not able to create the foreign key.
Thus you need to do:
CONSTRAINT COURSEA_PK PRIMARY KEY(course_id, term),
CONSTRAINT COURSEA_FK1 FOREIGN KEY(year, term)
REFERENCES CALENDAR(year, term),
CONSTRAINT COURSEA_FK2 FOREIGN KEY(course_id)
REFERENCES COURSE(course_id),
CONSTRAINT COURSEA_FK4 FOREIGN KEY(teacher_id)
REFERENCES TEACHER(teacher_id)
A foreign key must reference a primary key in the foreign table:
CONSTRAINT COURSEA_FK1 FOREIGN KEY(term) REFERENCES CALENDAR(term)
And term is not the PK of table Calendar. The correct form should be:
CONSTRAINT COURSEA_FK1 FOREIGN KEY(year,term) REFERENCES CALENDAR(year,term)

#1005 - Can't create table on ALTER TABLE when connecting table via FOREIGN KEY

I am working on a homework assignment. I have to build a database for a video store. All of the following works:
CREATE TABLE Stock
(
PKStock_ID VARCHAR(8) NOT NULL,
FKTitle VARCHAR(8) NOT NULL,
NoOfDVD INT(10) NOT NULL,
NoOfVHS INT(10) NOT NULL,
PRIMARY KEY (PKStock_ID)
);
CREATE TABLE Inventory
(
PKUnique_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Distributor_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
InStock CHAR(1) NOT NULL,
DateOut TIMESTAMP,
DateBack TIMESTAMP,
Customer_ID VARCHAR(8) NOT NULL,
Rental_Price DECIMAL(4,2) NOT NULL,
PRIMARY KEY (PKUnique_ID)
);
CREATE TABLE Movie
(
PKTitle_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
Title VARCHAR(30),
Genre VARCHAR(8),
YearReleased INT,
Length INT,
PRIMARY KEY (PKTitle_ID)
);
CREATE TABLE Actors
(
PKActor_ID VARCHAR(8) NOT NULL,
FKActor_ID VARCHAR(8) NOT NULL,
Actors VARCHAR(30),
PRIMARY KEY (PKActor_ID)
);
CREATE TABLE Awards
(
PKAward_ID VARCHAR(8) NOT NULL,
FKAward_ID VARCHAR(8) NOT NULL,
Awards VARCHAR(30),
PRIMARY KEY (PKAward_ID)
);
CREATE TABLE Directors
(
PKDirector_ID VARCHAR(8) NOT NULL,
FKDirector_ID VARCHAR(8) NOT NULL,
Directors VARCHAR(30),
PRIMARY KEY (PKDirector_ID)
);
CREATE TABLE ElectronicCatalogue
(
PKElectronicCatalogue VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Price DECIMAL(6,2) NOT NULL,
PRIMARY KEY (PKElectronicCatalogue)
);
CREATE TABLE Distributors
(
PKDistributor_ID VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
NameOfDistributer VARCHAR(30) NOT NULL,
Horror CHAR(1) NOT NULL,
Drama CHAR(1) NOT NULL,
Comedy CHAR(1) NOT NULL,
Action CHAR(1) NOT NULL,
Thrillers CHAR(1) NOT NULL,
PRIMARY KEY (PKDistributor_ID)
);
CREATE TABLE Customers
(
PKCustomer_ID VARCHAR(8) NOT NULL,
FKUnique_ID VARCHAR(8) NOT NULL,
Name VARCHAR(30),
Address VARCHAR(100),
Phone INT NOT NULL,
PRIMARY KEY (PKCustomer_ID)
);
CREATE TABLE Fees
(
PKFee_ID VARCHAR(8) NOT NULL,
FK_ID VARCHAR(8) NOT NULL,
Damages DECIMAL(10,2) NOT NULL,
Late DECIMAL(10,2) NOT NULL,
PRIMARY KEY (PKFee_ID)
);
ALTER TABLE Stock
ADD FOREIGN KEY (FKTitle)
REFERENCES Inventory(PKUnique_ID);
ALTER TABLE Movie
ADD FOREIGN KEY (FKTitle_ID)
REFERENCES Stock (PKStock_ID);
ALTER TABLE Actors
ADD FOREIGN KEY (FKActor_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Awards
ADD FOREIGN KEY (FKAward_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Directors
ADD FOREIGN KEY (FKDirector_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE ElectronicCatalogue
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES Inventory (PKUnique_ID);
ALTER TABLE Distributors
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES ElectronicCatalogue (PKElectronicCatalogue);
I next want to connect the Inventory table to the customers table. When I do the following:
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
I get this error:
#1005 - Can't create table 'mm.#sql-9f69_110' (errno: 150)
What am I doing wrong?
Foreign key should point to a unique column (primary key or unique). Your Inventory (Customer_ID) is not unique.
I think you are trying to :
ALTER TABLE Inventory
ADD CONSTRAINT fk1_Inv FOREIGN KEY (Customer_ID)
REFERENCES Customers (PKCustomer_ID);
Not sure why you didn't get the full message but there's a command line tool bundled with MySQL that provides further information about cryptic error messages like this (or you can just Google for the error code):
C:>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
If you have the SUPER privilege, you can get further details with this query:
show engine innodb status
And in this case you see this:
LATEST FOREIGN KEY ERROR
------------------------
130226 21:00:25 Error in foreign key constraint of table test/#sql-1d98_1:
FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So you are missing an index as explained.
Edit: As other answers point out, if there's no index it's because you're linking to the wrong column.
As Álvaro G. Vicario says you are missing an index, this is because you are not correctly using foreign keys.
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
This should be:
ALTER TABLE Inventory
ADD FOREIGN KEY (Customer_ID)
REFERENCES Customer(PKCustomer_ID);
The foreign key checks if the customer in the Inventory table actually exists in the Customers table. Thus Inventory here is the table you want to add the foreign key too and it references in primary key in the Customer table.
What you are trying to do is reference the Customer_ID in Inventory, which is just an VARCHAR(8)column and not an Primary Key (Index).
You should double check your other alter statements as well.
This turns out that you have different collation settings between these tables. In my case we had latin_swedish_ci and utf8_general_ci