I am getting error when I create table with foreign key
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id,_user_email,_user_mobile));
_users table created successfully..there were no error..
But When I want to create employee table :
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_mobile VARCHAR(15) not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_mobile) references _users(_user_mobile));
Its showing error:
ERROR 1005 (HY000): Can't create table 'DB.employee' (errno: 150)
What am I doing wrong??
Hey In this case you just need to do one thing ,
you just need to add index to the reference column of the user table and then run the create table for employee
ALTER TABLE `_users` ADD INDEX (`_user_mobile`);
After running above query just run the below query :-
CREATE TABLE `employee`(
`_Id` INT(11) NOT NULL AUTO_INCREMENT,
`_user_mobile` VARCHAR(15) NOT NULL,
`_name` VARCHAR(15),
`_org` VARCHAR(10),
PRIMARY KEY (`_Id`),
FOREIGN KEY (`_user_mobile`) REFERENCES `_users`(`_user_mobile`) );
In this way you will get rid of the error 1005 of mysql which says that you need to have index on the reference column of parent table.
150 is a foreign key error:
C:\>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
Getting the exact error message is very tricky. You need to run this query:
show engine innodb status
... and search in the output:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
160627 14:09:32 Error in foreign key constraint of table test/employee:
foreign key (_user_mobile) references _users(_user_mobile)):
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.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Once you know that, it'd be easy to add the missing index:
ALTER TABLE `_users`
ADD UNIQUE INDEX `_user_email` (`_user_email`);
But I wouldn't if I were you. It's weird to use mobile phone number as key. Instead, just simplify the primary key:
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id));
... and use in the linked table:
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_id int(20) unsigned not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_id) references _users(_id));
The problem is in the foreign key part. If you remove that, table will be created without a problem.
If you need to use that foreign key, you need to use InnoDB as the storage engine of MySQL. InnoDB allows a foreign key constraint to reference a non-unique key as can be seen in here.
Related
I am trying to create tables with a primary key and foreign key in Postgresql. Originally was created in MySQL but I do not know how to convert can someone assist.
I converted the first table but the instructor table is giving me problems
CREATE TABLE instructor_detail (
id SERIAL PRIMARY KEY,
youtube_channel VARCHAR(128) NULL,
hobby VARCHAR(45) NULL
);
DROP TABLE IF EXISTS instructor;
`CREATE TABLE instructor (
id SERIAL PRIMARY KEY,
first_name VARCHAR(45) NULL,
last_name VARCHAR(45) NULL,
email VARCHAR(45) NULL,
instructor_detail_id INT NULL,
CREATE INDEX fk_detail_idx ON instructor (instructor_detail_id), CONSTRAINT fk_detail FOREIGN KEY (instructor_detail_id) REFERENCES instructor_detail (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);`
ERROR: syntax error at or near "CREATE"
LINE 7: CREATE INDEX fk_detail_idx ON instructor (instructor_detai...
The foreign key constraint will work in PostgreSQL, no change is required.
The KEY clause is a MySQL extension to create an index within CREATE TABLE, which PostgreSQL does not support.
You'll have to convert the KEY clause to a separate CREATE INDEX statement in PostgresSQL.
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
can anyone help with this error , when i run my code it comes up with error 1005 can't create table my code looks like this can anyone point out the source of this error im using codio mysql if that helps
CREATE TABLE IF NOT EXISTS entries (
entries_id INT NOT NULL AUTO_INCREMENT,
students_id INT UNSIGNED NOT NULL,
Date_of_exam DATETIME NOT NULL,
subjects_id INT UNSIGNED NOT NULL,
PRIMARY KEY (entries_id),
FOREIGN KEY (students_id) REFERENCES students(students_id),
FOREIGN KEY (subjects_id) REFERENCES subjects(subjects_id));
this is the error
mysql> SOURCE task7
ERROR 1005 (HY000): Can't create table 'exams.entries' (errno: 150)
This error related to foreign keys. Check following items:
Name of tables and columns that exist on foreign keys are correct.
Type of foreign keys columns are same.
Data of foreign keys not conflict with them.
Note: You can disable check foreign key on query. Sure enable this option after query.
SET FOREIGN_KEY_CHECKS=0;
CREATE TABLE IF NOT EXISTS entries (
entries_id INT NOT NULL AUTO_INCREMENT,
students_id INT UNSIGNED NOT NULL,
Date_of_exam DATETIME NOT NULL,
subjects_id INT UNSIGNED NOT NULL,
PRIMARY KEY (entries_id),
FOREIGN KEY (students_id) REFERENCES students(students_id),
FOREIGN KEY (subjects_id) REFERENCES subjects(subjects_id)
);
SET FOREIGN_KEY_CHECKS=1;
The error itself is related with the foreign keys (as removing them creates the table with no errors).
Main possible causes:
One of the referenced tables doesn't exists
The field of the referenced tables doesn't exists
The data types of the referenced table doesn't match (I assume is this).
As i can see your primary key on your table is INT, assuming you use INT as your primary keys, students_id is INT UNSIGNED, possibly the cause of your error.
I am developing a patch version which is by create or update existing table by using raw sql.When I ran these 3 queries like below
first query Success
CREATE TABLE ts_overtime_scheme_histories( id int AUTO_INCREMENT NOT NULL,
name VARCHAR(255),
workdays INT,
break_payable VARCHAR(25),
roundable VARCHAR(25),
round_rule VARCHAR(10), round_minute INT,
type enum('ratio','fixed') DEFAULT 'ratio',
overtime_request_id INT UNSIGNED NOT NULL, PRIMARY KEY(id),
FOREIGN KEY(overtime_request_id) REFERENCES ts_overtime_requests(id) );
Second query success
CREATE TABLE ts_overtime_scheme_details_histories( id INT AUTO_INCREMENT NOT NULL,
hour FLOAT,
ratio FLOAT,
overtime_scheme_history_id INT(11) UNSIGNED NOT NULL,
PRIMARY KEY(id));
And now I am trying to connect second table to the first table. So the first table has foreign key on the second table. So I ran the third query
ALTER TABLE ts_overtime_scheme_details_histories ADD FOREIGN KEY (`overtime_scheme_history_id`) REFERENCES `ts_overtime_scheme_histories` (`id`) ON DELETE CASCADE;
But somehow it failed. The error report is below
General error: 1005 Can't create table `db_test`.`#sql-ea4_28` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: ALTER TABLE ts_overtime_scheme_details_histories
ADD FOREIGN KEY (`overtime_scheme_history_id`) REFERENCES `ts_overtime_scheme_histories` (`id`)
ON DELETE CASCADE;)
Can somebody help me to find what I miss? At first, I suspect the primary and foreign key data length is not similar, but when I double checked, it is correct.
Edit:
table ts_overtime_requests was created using laravel framework.
Column datatype of the foreign key column must match exactly the datatype of referenced key column.
In this case, the reported behavior (Error 1005) is expected because there's a difference in the datatypes of the two columns.
One of the columns is signed integer, the other column is UNSIGNED integer.
Quick fix would be to change the datatype of overtime_scheme_history_id so that is is signed. (Remove the UNSIGNED keyword.)
I am stuck with this error no 150 problem in mysql and I know there have been questions
which discuss this problem but I still can't find where I am wrong. Here is the database I am trying to create:
create table business (
ident varchar(40) NOT NULL,
name varchar(50) NOT NULL,
rating INT UNSIGNED NOT NULL,
PRIMARY KEY(ident)
) ENGINE=InnoDB;
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE
) ENGINE=InnoDB;
create table d_options (
business_id varchar(40) NOT NULL,
dealid varchar(20) NOT NULL,
option_title varchar(40) NOT NULL,
PRIMARY KEY(business_id, dealid, option_title),
FOREIGN KEY(business_id) REFERENCES business(ident) ON DELETE CASCADE,
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) ENGINE=InnoDB;
I get error: ERROR 1005 (HY000): Can't create table 'test.d_options' (errno: 150)
I know for foreign key constraints to be satisfied there should be a index in the parent table as per mysql documentation, but I think that there is by default indexing
on primary key.
The result of innodb status is:
120530 0:47:48 Error in foreign key constraint of table test/d_options:
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) 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.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Any help is appriciated.
You have a compound primary key on (business_id, deal_id) and they are indexed as a pair, but to satisfy the FK, you need another index on deal_id alone:
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE,
/* Add an index on deals_id, separate from the compound PK */
INDEX idx_deals_id (deals_id)
) ENGINE=InnoDB;