InnoDB CREATE TABLE throwing error 150 - mysql

This create table is throwing an error 150:
CREATE TABLE IF NOT EXISTS published(
isbn VARCHAR(13) NOT NULL,
publisherid INTEGER NOT NULL,
year INTEGER NOT NULL,
lastupdate TIMESTAMP NOT NULL,
lastupdateby INTEGER NOT NULL,
FOREIGN KEY (lastupdateby) REFERENCES librarians (librarianid),
FOREIGN KEY (isbn) REFERENCES books,
FOREIGN KEY (publisherid) REFERENCES publishers,
PRIMARY KEY (isbn, publisherid)
) ENGINE = INNODB;
I've checked that the tables it references (librarians, books, and publishers) are already created when SQL gets to this bit. Here are their DDLs:
CREATE TABLE IF NOT EXISTS librarians(
librarianid INTEGER AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
canread BOOLEAN NOT NULL,
canwrite BOOLEAN NOT NULL,
canexec BOOLEAN NOT NULL,
lastupdate TIMESTAMP NOT NULL,
lastupdateby INTEGER NOT NULL,
FOREIGN KEY (lastupdateby) REFERENCES librarians (librarianid)
) ENGINE = INNODB;
CREATE TABLE IF NOT EXISTS books(
isbn VARCHAR(13) PRIMARY KEY,
title VARCHAR(255) NOT NULL,
lastupdate TIMESTAMP NOT NULL,
lastupdateby INTEGER NOT NULL,
FOREIGN KEY (lastupdateby) REFERENCES librarians (librarianid)
) ENGINE = INNODB;
CREATE TABLE IF NOT EXISTS publishers(
publisherid INTEGER PRIMARY KEY AUTO_INCREMENT,
publishername VARCHAR(255) UNIQUE NOT NULL,
lastupdate TIMESTAMP NOT NULL,
lastupdateby INTEGER NOT NULL,
FOREIGN KEY (lastupdateby) REFERENCES librarians (librarianid)
) ENGINE = INNODB;
Further, I've checked the following guidelines I found here:
The referenced tables should be InnoDB as well. Well, I even had that explicitly specified.
Referenced tables must have an index and primary key. The foreign key fields are the (sole) primary keys of their respective reference tables. Unless I misunderstand this requirement, that should fulfill it.
SQL data types of FK column and referenced PK column must be identical. Unless I checked it wrong, this, too should be okay.
lastupdateby INTEGER NOT NULL --> librarianid INTEGER AUTO_INCREMENT PRIMARY KEY
isbn VARCHAR(13) NOT NULL --> isbn VARCHAR(13) PRIMARY KEY
publisherid INTEGER NOT NULL --> publisherid INTEGER PRIMARY KEY AUTO_INCREMENT
So, what did I miss? What can be the cause of this error 150?

You are missing column references in the foreign key specifications for tables books and publishers. You need to change those lines as below:
FOREIGN KEY (isbn) REFERENCES books (isbn),
FOREIGN KEY (publisherid) REFERENCES publishers(publisherid),

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.

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)
)

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 Foreign Keys Issue

I have 3 table: CD, Song and Song_Details which is a relationship between CD & Song:
create table Song(
ID int not null auto_increment,
Title varchar(255) not null,
Length float not null,
primary key (ID, Title)
);
create table CD(
Title varchar(255) not null,
CD_Number int not null,
primary key (Title, CD_Number)
);
Create table Song_Details(
CD_Title varchar(255) not null,
Song_Title varchar(255) not null,
Track_Number int not null,
primary key(CD_Title, Song_Title),
foreign key(CD_Title) references CD(Title),
foreign key(Song_Title) references Song(Title)
);
I have managed to find out that this line in Song_Details:
foreign key(Song_Title) references Song(Title) is throwing the Error 1215(HY000): Cannot add foreign key constraint;
Could anyone help me see based on my table, what could be causing this issue?
Two things. The auto_increment key would normally be the foreign key. Second, you need to make your reference to all the keys defined as the primary or unique key for the table (I don't advise making foreign key references to non-unique keys although MySQL does all that).
So:
create table Song (
Song_ID int not null auto_increment,
Title varchar(255) not null,
Length float not null,
primary key (ID),
unique (title)
);
create table CD (
CD_Id int auto_increment primary key,
Title varchar(255) not null,
CD_Number int not null,
unique (Title, CD_Number)
);
Create table Song_Details(
CD_ID varchar(255) not null,
Song_Id varchar(255) not null,
Track_Number int not null,
primary key(CD_ID, Song_ID),
foreign key(CD_ID) references CD(CD_ID),
foreign key(Song_ID) references Song(Song_ID)
);
Notes:
Use the primary key relationships for the foreign key definitions.
I like to have the primary keys include the table name. That way, the primary key can have the same name as the corresponding foreign keys.
Don't put the titles in more than one place. They belong in the entity tables. Autoincremented ids can then be used to access the titles.

#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