Cannot add foreign key constraint - MySQL ERROR 1215 (HY000) - mysql

I am trying to create database for gym management system, but I can't figure out why I am getting this error. I've tried to search for the answer here, but I couldn't find it.
ERROR 1215 (HY000): Cannot add foreign key constraint
CREATE TABLE sales(
saleId int(100) NOT NULL AUTO_INCREMENT,
accountNo int(100) NOT NULL,
payName VARCHAR(100) NOT NULL,
nextPayment DATE,
supplementName VARCHAR(250),
qty int(11),
workoutName VARCHAR(100),
sDate datetime NOT NULL DEFAULT NOW(),
totalAmount DECIMAL(11,2) NOT NULL,
CONSTRAINT PRIMARY KEY(saleId, accountNo, payName),
CONSTRAINT FOREIGN KEY(accountNo) REFERENCES accounts(accountNo) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(payName) REFERENCES paymentFor(payName) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(supplementName) REFERENCES supplements(supplementName) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(workoutName) REFERENCES workouts(workoutName) ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE sales AUTO_INCREMENT = 2001;
Here is the parent tables.
CREATE TABLE accounts(
accountNo int(100) NOT NULL AUTO_INCREMENT,
accountType VARCHAR(100) NOT NULL,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(60) NOT NULL,
birthdate DATE NOT NULL,
gender VARCHAR(7),
city VARCHAR(50) NOT NULL,
street VARCHAR(50),
cellPhone VARCHAR(10),
emergencyPhone VARCHAR(10),
email VARCHAR(150) NOT NULL,
description VARCHAR(350),
occupation VARCHAR(50),
createdOn datetime NOT NULL DEFAULT NOW(),
CONSTRAINT PRIMARY KEY(accountNo)
);
ALTER TABLE accounts AUTO_INCREMENT = 1001;
CREATE TABLE supplements(
supplementId int(100) NOT NULL AUTO_INCREMENT,
supplementName VARCHAR(250) NOT NULL,
manufacture VARCHAR(100),
description VARCHAR(150),
qtyOnHand INT(5),
unitPrice DECIMAL(11,2),
manufactureDate DATE,
expirationDate DATE,
CONSTRAINT PRIMARY KEY(supplementId, supplementName)
);
ALTER TABLE supplements AUTO_INCREMENT = 3001;
CREATE TABLE workouts(
workoutId int(100) NOT NULL AUTO_INCREMENT,
workoutName VARCHAR(100) NOT NULL,
description VARCHAR(7500) NOT NULL,
duration VARCHAR(30),
CONSTRAINT PRIMARY KEY(workoutId, workoutName)
);
ALTER TABLE workouts AUTO_INCREMENT = 4001;
CREATE TABLE paymentFor(
payId int(100) NOT NULL AUTO_INCREMENT,
payName VARCHAR(100) NOT NULL,
amount DECIMAL(11,2),
CONSTRAINT PRIMARY KEY(payId, payName)
);
ALTER TABLE paymentFor AUTO_INCREMENT = 5001;
Can you guys help me with this problem? Thanks.

If you ever want to find out, why that error was , all you have to do is run below command and look for "LATEST FOREIGN KEY ERROR"
Command to run :-
mysql> SHOW ENGINE INNODB STATUS
You will know the reason for your such errors.

For a field to be defined as a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES parent_tbl_name (index_col_name,...)
Define an INDEX on workouts.workoutName, paymentFor.paymentName, and supplements.supplementName respectively. And make sure that child column definitions must match with those of their parent column definitions.
Change workouts table definition as below:
CREATE TABLE workouts(
workoutId int(100) NOT NULL AUTO_INCREMENT,
workoutName VARCHAR(100) NOT NULL,
description VARCHAR(7500) NOT NULL,
duration VARCHAR(30),
KEY ( workoutName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(workoutId, workoutName)
);
Change supplements table definition as below:
CREATE TABLE supplements(
supplementId int(100) NOT NULL AUTO_INCREMENT,
supplementName VARCHAR(250) NOT NULL,
manufacture VARCHAR(100),
description VARCHAR(150),
qtyOnHand INT(5),
unitPrice DECIMAL(11,2),
manufactureDate DATE,
expirationDate DATE,
KEY ( supplementName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(supplementId, supplementName)
);
Change paymentFor table definition as below:
CREATE TABLE paymentFor(
payId int(100) NOT NULL AUTO_INCREMENT,
payName VARCHAR(100) NOT NULL,
amount DECIMAL(11,2),
KEY ( payName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(payId, payName)
);
Now, change child table definition as below:
CREATE TABLE sales(
saleId int(100) NOT NULL AUTO_INCREMENT,
accountNo int(100) NOT NULL,
payName VARCHAR(100) NOT NULL,
nextPayment DATE,
supplementName VARCHAR(250) NOT NULL,
qty int(11),
workoutName VARCHAR(100) NOT NULL,
sDate datetime NOT NULL DEFAULT NOW(),
totalAmount DECIMAL(11,2) NOT NULL,
CONSTRAINT PRIMARY KEY(saleId, accountNo, payName),
CONSTRAINT FOREIGN KEY(accountNo)
REFERENCES accounts(accountNo)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(payName)
REFERENCES paymentFor(payName)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(supplementName)
REFERENCES supplements(supplementName)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(workoutName)
REFERENCES workouts(workoutName)
ON DELETE CASCADE ON UPDATE CASCADE
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

Foreign Keys are a way of implementing relationships/constraints between columns in different tables.
There are different categories of constraints that influence how they’re enforced when a row is updated or deleted from the parent table:
◾Cascade: If a row is deleted from the parent then any rows in the child table with a matching FK value will also be deleted. Similarly for changes to the value in the parent table.
◾Restrict: A row cannot be deleted from the parent table if this would break a FK constraint with the child table. Similarly for changes to the value in the parent table.
◾No Action: Very similar to “Restrict” except that any events/triggers on the parent table will be executed before the constraint is enforced – giving the application writer the option to resolve any FK constraint conflicts using a stored procedure.
◾Set NULL: If NULL is a permitted value for the FK column in the child table then it will be set to NULL if the associated data in the parent table is updated or deleted.
◾Set Default: If there is a default value for the FK column in the child table then it will be used if the associated data in the parent table is updated or deleted. Note that this is not implemented in this version – the constraint can be added to the schema but any subsequent deletion or update to the column in the parent table will fail.

Some times you will get this error "#1215 - Cannot add foreign key constraint" because of table TYPE (InnoDB, MyISAM,..) mismatch.
So change your table type into same and try applying for foreign key constraint
mysql> ALTER TABLE table_name ENGINE=InnoDB;
mysql> ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

This might work for some people. Simply add the default character set as utf8
DEFAULT CHARACTER SET = utf8;

I was getting the same error. The reason was I was referring to a column in a table created with charset utf8 from a table created using charset latin.
The tables created using mySQL workbench create table utility have default charset latin.
Easy approach to find this out if you are using workbench is to view the table create statement of any table. You will have the default charset string at the end.

I'm not answering the above question but just for people who will run into the same mysql error.
All I did was to change the referenced table engine to innodb.

I encounter this error I add foreign key constraint for a column that has 'not null constraint' but I specified the 'on delete set null' in the foreign constraint. This is a contradiction that it may not be obvious at first.
Here are my two tables:
CREATE TABLE study (
id int(11) NOT NULL AUTO_INCREMENT primary key,
name varchar(100) NOT NULL,
introduction text,
objective varchar(250) DEFAULT NULL,
method text,
result text,
conclusion varchar(250) DEFAULT NULL,
future_action varchar(100) DEFAULT NULL
);
drop table client_study;
CREATE TABLE client_study (
id int(11) NOT NULL AUTO_INCREMENT primary key,
client_id int(11),
study_id int(11) not null, --If delete 'not null' error goes away!
contact_person int(11),
effective_date datetime DEFAULT CURRENT_TIMESTAMP,
trial_site int(11) DEFAULT NULL,
UNIQUE KEY unqidx_client_study (client_id,study_id)
);
ALTER TABLE client_study
ADD CONSTRAINT FOREIGN KEY (study_id) REFERENCES study(id)
ON DELETE SET NULL ON UPDATE CASCADE;
ERROR 1215 (HY000): Cannot add foreign key constraint
If you remove the NOT NULL constraint on the study_id column in the client_study table, the foreign key can be added. The other alternative is to keep the not null constraint on the client_table, but modify the foreign key definition to on delete no action or other choices.

Related

Failed to add the foreign key constraint in MySQL: error 3780

I am getting the error:
Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.
drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;
create table Provider
(
privider_id serial not null primary key,
login_password varchar(20) not null
constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'),
fathersname varchar(20) not null,
name_of_contact_face varchar(10) not null,
surname varchar(15),
e_mail varchar(25) unique
constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\#gmail.com\s?')
);
create table Category
(
title varchar(20),
category_id serial not null primary key
);
create table Product
(
barecode serial not null primary key,
provider_id bigint not null,
manufacturer varchar(25) not null,
category_id bigint not null,
dimensions varchar(10) not null,
amount int not null,
date_of_registration datetime not null,
#constraint 'provider_for_product'
foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);
The datatypes of the two columns referenced in a foreign key constraint need to match
In MySQL, SERIAL is an alias for BIGINT UNSIGNED AUTO_INCREMENT.
To make a foreign key that references this column, it must be BIGINT UNSIGNED, not a signed BIGINT.
You might like to view a checklist of foreign key mistakes I contributed to: https://stackoverflow.com/a/4673775/20860
I also cover foreign key mistakes in more detail in a chapter of my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

Not able to create table with foreign key constraints for two columns?

I have created below airports table :
CREATE TABLE airports(
airport_id int(4) unsigned AUTO_INCREMENT NOT NULL,
airport_name varchar(250),
primary key(airport_id)
)ENGINE=InnoDB;
But when I'm creating schedule table with foreign key constraints,Its not able to create. Below is the script :
CREATE TABLE schedule (
flight_id int(3) unsigned AUTO_INCREMENT NOT NULL,
origin_airport_id int(4),
destination_airport_id int(4) ,
departure_time char(15) not null,
arrival_time char(15) not null,
duration varchar(20) not null,
flight_fare decimal(9,2) not null,
PRIMARY KEY (flight_id),
FOREIGN KEY(origin_airport_id,destination_airport_id) REFERENCES airports(airport_id,airport_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
Below is the error message from show 'engine innodb status;', when I try to create the schedule table.
Error in foreign key constraint of table airport_db/schedule:
FOREIGN KEY(origin_airport_id,destination_airport_id) REFERENCES airports(airport_id,airport_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB:
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.6/en/innodb-foreign- key-constraints.html for correct foreign key definition.
Foreign keys need to reference the primary (or unique) keys of a table. There are no duplicates. And, the types have to exactly match (int doesn't match int unsigned).
So, try this instead:
CREATE TABLE schedule (
flight_id int(3) unsigned AUTO_INCREMENT NOT NULL,
origin_airport_id int(4) unsigned,
destination_airport_id int(4) unsigned,
departure_time char(15) not null,
arrival_time char(15) not null,
duration varchar(20) not null,
flight_fare decimal(9,2) not null,
PRIMARY KEY (flight_id),
FOREIGN KEY(origin_airport_id) REFERENCES airports(airport_id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY(destination_airport_id) REFERENCES airports(airport_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
Here is a SQL Fiddle.

Mysql create table with multiple foreign key on delete set null

I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:
CREATE TABLE Worker (
WorkerID smallint auto_increment,
WorkerType varchar(45) NOT NULL,
WorkerName varchar(45) NOT NULL,
Position varchar(45) NOT NULL,
TaxFileNumber int NOT NULL,
Address varchar(100) ,
Phone varchar(20) ,
SupervisorID smallint ,
PRIMARY KEY (WorkerID),
FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
CREATE TABLE Grape (
GrapeID smallint NOT NULL,
GrapeType varchar(45) NOT NULL,
JuiceConversionRatio int,
StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),
AgingRequirement int,
PRIMARY KEY (GrapeID)
)Engine=InnoDB;
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint NOT NULL,
GrapeID smallint NOT NULL,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.
Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.
Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint,
GrapeID smallint,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
SQLFiddle demo
Try with create table(innoDB enginer) without foreign key and use the update table with constraint syntax, for example:
ALTER TABLE `vineyard`
ADD CONSTRAINT `relation_farmer_has_many_vineyards`
FOREIGN KEY (`farmer_id`)
REFERENCES `worker` (`worker_id`)
ON DELETE SET NULL
ON UPDATE CASCADE;
Reference:
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Trick: is not recommended to use capital letters(or camel case) in the names of the tables that the behavior differs from the operating system being used:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html
Visit :
https://developer.android.com/training/basics/data-storage/databases.html#DefineContract
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Visit :
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
CREATE TABLE `ffxi_characterJob` (
`serverID` int(11) NOT NULL,
`userid` int(10)unsigned NOT NULL,
`characterName` varchar(255) NOT NULL,
`jobAbbr` char(4) NOT NULL,
`jobLevel` int(11) default '0',
PRIMARY KEY (`serverID`,`userid`,`characterName`,`jobAbbr`),
INDEX (`jobAbbr`),
CONSTRAINT FOREIGN KEY (`serverID`,`userid`,`characterName`) REFERENCES `ffxi_characters` (`serverID`,`userid`,`characterName`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (`jobAbbr`) REFERENCES `ffxi_jobType` (`jobAbbr`) ON DELETE CASCADE ON UPDATE CASCADE
) TYPE=InnoDB;

#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

mysql innoDB error 1005

I'm trying to find what causes error 1005 on creation of my tables:
CREATE TABLE hospitals(
hosp_id INT NOT NULL AUTO_INCREMENT,
hosp_name VARCHAR(100) NOT NULL,
hosp_address VARCHAR(100) NOT NULL,
hosp_ph_number VARCHAR(8) NOT NULL,
PRIMARY KEY(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE transport(
tr_regnumber VARCHAR(8) NOT NULL,
tr_brand VARCHAR(15) NOT NULL,
tr_description VARCHAR(25),
hosp_id INT,
PRIMARY KEY (tr_regnumber),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE buildings(
build_id INT NOT NULL AUTO_INCREMENT,
hosp_id INT,
build_address VARCHAR(100) NOT NULL,
build_description VARCHAR(25),
PRIMARY KEY (build_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE patients(
pat_id INT NOT NULL AUTO_INCREMENT,
pat_fullname VARCHAR(150) NOT NULL,
diagnosis VARCHAR(150) NOT NULL,
emp_id INT,
pat_ph_number VARCHAR(8),
pat_address VARCHAR(100),
hosp_id INT,
pl_num INT,
PRIMARY KEY (pat_id),
FOREIGN KEY (pl_num) REFERENCES places(pl_number),
FOREIGN KEY (emp_id) REFERENCES employees(emp_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE places(
pl_number INT NOT NULL AUTO_INCREMENT,
pat_id INT NOT NULL,
hosp_id INT NOT NULL,
PRIMARY KEY (pl_number),
FOREIGN KEY (pat_id) REFERENCES patients(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE employees(
emp_id INT NOT NULL AUTO_INCREMENT,
emp_fullname VARCHAR(150) NOT NULL,
emp_position VARCHAR(100) NOT NULL,
emp_ph_number VARCHAR(8),
emp_home_address VARCHAR(100),
hosp_id INT NOT NULL,
PRIMARY KEY (emp_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
Here are errors:
ERROR 1005 (HY000): Can't create table 'hospital_db.patients' (errno: 150)
ERROR 1005 (HY000): Can't create table 'hospital_db.places' (errno: 150)
Here's output of SHOW INNODB STATUS:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
110829 11:52:01 Error in foreign key constraint of table hospital_db/places:
FOREIGN KEY (pat_id) REFERENCES patients(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8:
Cannot resolve table name close to:
(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8
I use MySQL v5.1.49.
This seems to be to do with the order you're creating the tables and the foreign key dependencies you have.
Try disabling foreign key checks before creating the tables and enabling them after like so:
SET foreign_key_checks = 0;
-- Your create queries here
SET foreign_key_checks = 1;
Cheers
I know this one is solved, but for the Googlers out here, I did this in mysql workbench:
Primary keys have 'not null' checked by default. Creating a foreign key in a child table and also checking it as 'not null' will cause this error. It took me ages to find this myself because its an exception of what people suggest (making sure everything in the column is of the same type as the parent key). So just leave 'not null' unchecked on the foreign key
thought this might help saving people some time :)
You create FK on table 'places' before creating this table. Table places is created after table patients which try to use table which doesn't exist yet.
It seems that you have crossing foreign keys. In this case it's better to create tables without FKs and than use ALter TABLE for adding FKs.