Unable to create foreign key reference with different column lables - mysql

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

Related

Error code 1005 - Can't create table

Having trouble adding a foreign key to my table.
CREATE TABLE event (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
issued DATETIME NOT NULL,
user VARCHAR(255) NOT NULL,
subject VARCHAR(255) NOT NULL,
attending BIGINT(255) NOT NULL,
attendees VARCHAR(255) NOT NULL,
organisers VARCHAR(255) NOT NULL,
place BIGINT(20) NOT NULL,
started DATETIME NOT NULL,
stopped DATETIME NOT NULL,
content LONGTEXT NOT NULL,
broadcasting TINYINT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (place)
REFERENCES place (id),
FOREIGN KEY (user)
REFERENCES user (username)
)
The foreign key for place is executing fine but once I try adding user as a foreign key I keep getting the same error:
Error Code: 1005. Can't create table 'iservices.event' (errno: 150)
Can anyone help?
Picture of user table:
User table
Picture of place table:
Place table
Is there anyway of expanding the errors in MySQL Workbench?
a foreign key has to be unique, so make username unique (which is probably not the best idea) or choose something different like the user id.
My advice: add a primary auto-increment key to the user table and use it as the foreign-key.
Referenced column must be unique. It's OK in your case.
Columns in child and parent table must be of the same type. In your case they are different.
Could you please make sure user and place tables exist and have corresponding columns set as primary key? The below snipper works fine:
CREATE TABLE user(username VARCHAR(255) PRIMARY KEY);
CREATE TABLE place(id BIGINT(20) PRIMARY KEY);
CREATE TABLE event (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
issued DATETIME NOT NULL,
user VARCHAR(255) NOT NULL,
subject VARCHAR(255) NOT NULL,
attending BIGINT(255) NOT NULL,
attendees VARCHAR(255) NOT NULL,
organisers VARCHAR(255) NOT NULL,
place BIGINT(20) NOT NULL,
started DATETIME NOT NULL,
stopped DATETIME NOT NULL,
content LONGTEXT NOT NULL,
broadcasting TINYINT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (place)
REFERENCES place (id),
FOREIGN KEY (user)
REFERENCES user (username)
)
Here's SQL Fiddle.
I had encountered a similar error.
This can occur when you are trying to add a non-primary key from the primary table as the foreign key in the secondary table.
To avoid this, the foreign key in the secondary table has to be the primary key in the primary table.

#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 creating a table (errno 150)

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

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

sql Error 1064 (42000) Syntax Error

CREATE TABLE IF NOT EXISTS message(
id INT NOT NULL auto_increment,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
PRIMARY KEY ('id')
FOREIGN KEY ('userid') REFERENCES users('id'));
I was just wondering if someone could help me in identifying a syntax error as I can not create a table.
Try to put , after the primary key declaration.
Update: I guess it should be
CREATE TABLE IF NOT EXISTS message (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users(id));
I'm assuming this is for MS SQL Server? If you get MS SQL Server Studio, you can script stuff which gives you an idea:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[message]') AND type in (N'U'))
CREATE TABLE message(
id INT IDENTITY NOT NULL,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (userid) REFERENCES users(id))
GO
You query should be as below
CREATE TABLE IF NOT EXISTS message (
id INT auto_increment PRIMARY KEY,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users(id));
Provided you have id as a primary key in users table.
CREATE TABLE users (id INT PRIMARY KEY)
Your query should look like this:
CREATE TABLE IF NOT EXISTS message(
id INT NOT NULL auto_increment,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
PRIMARY KEY ('id'),
FOREIGN KEY ('userid') REFERENCES users('id')
) Engine=InnoDB;
Note the , after PRIMARY KEY ('id').
Small trick
You don't have to specify foreign keys in table definitions. It's practical when you do it like this (because dump may export tables in order that foreign keys will fail on creating/inserting):
CREATE TABLE 1; -- With references to table 2
CREATE TABLE 2;
INSERT INTO 1;
INSERT INTO 2;
ALTER TABLE 1 ADD FOREIGN KEY (user_id) REFERENCES 2 2(id);
Try to change the name of your table, May be message is an in-built keyword in MySQL.
Update to this: I guess it should be
CREATE TABLE IF NOT EXISTS myMessage (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users(id));