MySQL creating a table (errno 150) - mysql

I would like to ask something that troubles me many many days...
Here is what I mean:
I create these two tables:
CREATE TABLE IF NOT EXISTS journal (
issn varchar(20) NOT NULL,
j_title varchar(100) NOT NULL,
j_publisher varchar(30) NOT NULL,
PRIMARY KEY (issn)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS volume (
volume_no int(11) NOT NULL,
issn varchar(20) NOT NULL,
year int(11) NOT NULL,
PRIMARY KEY (issn,volume_no),
FOREIGN KEY (issn) REFERENCES journal(issn)
) ENGINE=InnoDB;
When I try to create this:
CREATE TABLE IF NOT EXISTS issue (
issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issue_no,issn,volume_no),
FOREIGN KEY (issn) REFERENCES journal(issn),
FOREIGN KEY (volume_no) REFERENCES volume(volume_no)
) ENGINE=InnoDB;
it throws an error (errno 150)
The error is in the foreign key volume_no.
Without FOREIGN KEY (volume_no) REFERENCES volume(volume_no)
the table is created without a problem.... I can't explain what's going on... I have seen it many times again and again but nothing!! Does anybody know what's going on?
Thanks in advance!!

I could see that the foreign key doesnt include issn but which is actually included in primary key for volumn table.
CREATE TABLE IF NOT EXISTS issue ( issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issue_no,issn,volume_no),
FOREIGN KEY (issn,volume_no) REFERENCES volume(issn,volume_no) ) ENGINE=InnoDB;
Look at the below sql fiddle.
http://sqlfiddle.com/#!2/55a63

maybe volume_no needs to be UNSIGNED

FOREIGN keys must reference a PRIMARY or a UNIQUE key in the parent table.
You need only one Foreign Key at table issue, not two. And it should reference the Primary Key of volume:
CREATE TABLE IF NOT EXISTS issue (
issue_no int(11) NOT NULL,
issue_pages varchar(10) NOT NULL,
issue_date varchar(10) NOT NULL,
issn varchar(20) NOT NULL,
volume_no int(11) NOT NULL,
PRIMARY KEY (issn, volume_no, issue_no),
FOREIGN KEY (issn, volume_no)
REFERENCES volume(issn, volume_no)
) ENGINE=InnoDB;

If the PK of the parent table is more than one field, the order of the fields in the FK must be the same as the order in the PK.
issue: FOREIGN KEY (issn, volume_no) REFERENCES volume(issn, volume_no)
These conditions must be satisfied to not get error 150:
The two tables must be ENGINE=InnoDB.
The two tables must have the same charset.
The PK column(s) in the parent table and the FK column(s) must be the same data type.
The PK column(s) in the parent table and the FK column(s), if they have a define collation type, must have the same collation type;
If there is data already in the foreign key table, the FK column value(s) must match values in the parent table PK columns.
source: MySQL Creating tables with Foreign Keys giving errno: 150

I had about the same issue with my database. It wasn't about the definition of the foreign key, actually it was the definition of the primary key field.
CREATE TABLE tblProcesses (
fldProcessesID SMALLINT(5) UNIQUE NOT NULL AUTO_INCREMENT ,
CREATE TABLE tblProcessesMessage (
fldProcesses TEXT NOT NULL,
fldProcessesID VARCHAR(15) NOT NULL DEFAULT ,
The primary key in tblProcesses (fldProcessesID) did not have the UNSIGNED keyword while the foreign key in tblProcessesMessage (fldProcessesID) had the UNSIGNED keyword. This keyword was causing the problem - inconsistent type of field. So i added the UNSIGNED keyword to fldProcessesID in tblPreocesses:
CREATE TABLE tblProcesses (
fldProcessesID SMALLINT(5) UNSIGNED UNIQUE NOT NULL AUTO_INCREMENT,
I hope that this will help you solve your problems.
Best regards,
Nicholas

Related

errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps

sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:
Table users
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
cname varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
Table behaviours
CREATE TABLE behaviours (
id int(2) AUTO_INCREMENT PRIMARY KEY,
bName varchar(100) NOT NULL
);
Table severytys
CREATE TABLE severitys (
id int(2) AUTO_INCREMENT PRIMARY KEY,
severity varchar(10) NOT NULL
);
And here it shows errors:
CREATE TABLE child_behaviours(
id int(11) primary key auto_increment,
name varchar(50) not null,
cname varchar(50) not null,
bName varchar(100) NOT NULL,
severity varchar(10) NOT NULL,
start_at datetime,
stop_at datetime null,
FOREIGN KEY (id) REFERENCES users(id),
FOREIGN KEY (bName) REFERENCES behaviours(bName),
FOREIGN KEY (severity) REFERENCES severitys(severity)
);
Will be really pleasent to have an answer to this issue
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.
If you reference anything other than the PK, you need a really really good reason.
(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)
Now, child_behaviours has several errors:
Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.
Reference to behaviors(bName) instead of using its id
same thing for reference to severity
Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:
SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...
You have to refer to a primary key, when building a foreign key
CREATE TABLE child_behaviours(
userId int not null,
behaviourId int NOT NULL,
severityId int NOT NULL,
start_at datetime not null,
stop_at datetime,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
FOREIGN KEY (severityId) REFERENCES severitys(id)
);

Unable to create foreign key reference with different column lables

While I am creating schema "Cannot add foreign key constraint" error I am getting.
Query is :
CREATE database sample;
USE sample;
CREATE TABLE sys_admin_user_t (
sys_admin_id MEDIUMINT NOT NULL,
admin_name VARCHAR(255) NOT NULL,
admin_password VARCHAR(255) NOT NULL,
PRIMARY KEY (sys_admin_id)
);
CREATE TABLE sys_user_roles_t (
role_id MEDIUMINT NOT NULL,
privilege_id MEDIUMINT NOT NULL,
role_name VARCHAR(255) NOT NULL,
role_description VARCHAR(255) NOT NULL,
created_by MEDIUMINT NOT NULL,
created_date DATE NOT NULL,
modified_by MEDIUMINT NOT NULL,
FOREIGN KEY (privilege_id) REFERENCES privileges_t (privilege_id),
FOREIGN KEY (created_by) REFERENCES sys_admin_user_t(sys_admin_id),
FOREIGN KEY (modified_by) REFERENCES sys_admin_user_t(sys_admin_id),
PRIMARY KEY (role_id)
);
Kindly some one help me to resolve this.
This can occur in the following cases:
You do not create the table privileges_t
In your table privileges_t does not exists primary key by field privilege_id
The field privilege_id from table sys_user_roles_t are not exactly the same data type as in table privileges_t
You are not using InnoDB as the engine on all tables
And to find the specific error run this:
SHOW ENGINE INNODB STATUS\G

Simple add foreign key returns #1215 cannot add foreign key constraint

I am sure I am missing something simple.
RequestLog table:
CREATE TABLE `requestlog` (
`RequestID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`RequestName` varchar(30) NOT NULL,
`RequestData` varchar(150) NOT NULL,
`RequestDate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Version` varchar(15) NOT NULL,
PRIMARY KEY (`RequestID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
ResponseLog table:
CREATE TABLE `responselog` (
`ResponseID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`FK_RequestID` int(10) NOT NULL,
`ResponseText` text NOT NULL,
PRIMARY KEY (`ResponseID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Trying to add a foreign key on ResponseLog.FK_RequestID with
ALTER TABLE ResponseLog
ADD FOREIGN KEY (FK_RequestID) REFERENCES RequestLog(RequestID)
Don't shoot me, what am I missing?
ALTER TABLE references tables ResponseLog and RequestLog. Your CREATE TABLE statements create tables named requestlog and responselog. Try changing your ALTER TABLE statement so that it uses table identifiers with the same case.
Also, and it is probably the main problem, the referenced fields have different data types. One is an int, the other an unsigned int. Data types have to match, otherwise the fields could become inconsistent. MySQL knows this and prevents you from creating a broken foreign key.

#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 error #1064

Hi all I can't find the error in this table creation bit, seems really straight forward to be, here's what it's giving me:
ERROR 1064 at line 3: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'FOREIGN KEY(courses_courseDepartmentAbbv))' at
line 8
DROP TABLE IF EXISTS courses;
CREATE TABLE courses(
courses_courseNumber INT NOT NULL AUTO_INCREMENT,
courses_courseTitle VARCHAR(25) NOT NULL,
courses_courseTeacher VARCHAR(30) NOT NULL,
courses_courseCostOfBooks DECIMAL(5,2) NOT NULL,
courses_courseDepartmentAbbv CHAR(4) NOT NULL,
PRIMARY KEY (courses_courseNumber),
FOREIGN KEY (courses_courseTeacher),
FOREIGN KEY (courses_courseDepartmentAbbv)
);
DROP TABLE IF EXISTS departments;
CREATE TABLE departments(
departments_departmentAbbv CHAR(4) NOT NULL,
departments_departmentFullName VARCHAR(15) NOT NULL,
PRIMARY KEY (departments_departmentAbbv),
FOREIGN KEY (departments_departmentAbbv) REFERENCES (courses_courseDepartmentAbbv)
);
DROP TABLE IF EXISTS teachers;
CREATE TABLE teachers(
teachers_teacherName VARCHAR(20) NOT NULL,
teachers_teacherHomeroom SMALLINT(3) NOT NULL,
teachers_teacherHomeroomGrade SMALLINT(1) NOT NULL,
teachers_teacherFullTime BOOL NOT NULL,
PRIMARY KEY (teachers_teacherName),
FOREIGN KEY (teachers_teacherName) REFERENCES (courses_courseTeacher)
);
You need to have a References after each Foreign key. You are missing that in the beginning setup of courses. Here is the documentation
I think this is more of what you want. Your order of creation was not correct. You had foreign keys in the wrong location due to this. You only set up foreign key mappings on the tables with the relations to the PK. You only need to set up the PK on your other tables. As long as you create the tables in the right order, then you can do this, as below.
So, teachers and departments have primary keys that are foreign keys within the courses table. teachers and departments does not need to worry about the foreign key. You leave that up to the table that actually has the reference (courses)
DROP TABLE IF EXISTS teachers;
CREATE TABLE teachers(
teachers_teacherName VARCHAR(20) NOT NULL,
teachers_teacherHomeroom SMALLINT(3) NOT NULL,
teachers_teacherHomeroomGrade SMALLINT(1) NOT NULL,
teachers_teacherFullTime BOOL NOT NULL,
PRIMARY KEY (teachers_teacherName)
--FOREIGN KEY (teachers_teacherName) REFERENCES courses (courses_courseTeacher)
--This is not where you set up the FK for courses
);
DROP TABLE IF EXISTS departments;
CREATE TABLE departments(
departments_departmentAbbv CHAR(4) NOT NULL,
departments_departmentFullName VARCHAR(15) NOT NULL,
PRIMARY KEY (departments_departmentAbbv)
--FOREIGN KEY (departments_departmentAbbv) REFERENCES courses (courses_courseDepartmentAbbv)
--This is not where you set up the FK for courses
);
CREATE TABLE courses(
courses_courseNumber INT NOT NULL AUTO_INCREMENT,
courses_courseTitle VARCHAR(25) NOT NULL,
courses_courseTeacher VARCHAR(30) NOT NULL,
courses_courseCostOfBooks DECIMAL(5,2) NOT NULL,
courses_courseDepartmentAbbv CHAR(4) NOT NULL,
PRIMARY KEY (courses_courseNumber),
FOREIGN KEY (courses_courseTeacher)
REFERENCES teachers (teachers_teacherName)
FOREIGN KEY (courses_courseDepartmentAbbv)
REFERENCES departments(departments_departmentAbbv)
);
You need to give a REFERENCES clause for your FOREIGN KEY clauses
FOREIGN KEY (courses_courseTeacher)
FOREIGN KEY (courses_courseDepartmentAbbv)
Define engine type that should be innodb which supports FOREIGN KEY constraints.
Follow Syntax defined here