unable to set foreign key mysql - mysql

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

Related

sql error that i cant solve (7)

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.

mysql table is not creating

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.

MySQL : Error Code 1215 : Cannot add foreign key constraint

I'm trying to make a simple SQL schema, but I'm having some problem with defining foreign keys. I really don't have that much MySQL knowledge, so I thought I'd ask her for some help. I get Error Code 1215 when I try to create the foreign key roomID and 'guestEmail' in the HotelManagement.Reservation table creation.
CREATE database HotelManagement;
CREATE TABLE HotelManagement.Room (
roomID INT not null auto_increment,
roomTaken TINYINT(1),
beds INT not null,
size INT not null,
roomRank INT not null,
PRIMARY KEY(roomID));
CREATE TABLE HotelManagement.HotelTask (
taskType INT not null,
taskStatus TINYINT(1) not null,
whichRoom INT not null,
note VARCHAR(255),
PRIMARY KEY (taskType),
FOREIGN KEY (whichRoom) REFERENCES HotelManagement.Room(roomID));
CREATE TABLE HotelManagement.Guest (
firstName varchar(25) not null,
lastName varchar(25) not null,
userPassword varchar(25) not null,
email varchar(25) not null,
reservation INT,
PRIMARY KEY (userPassword, email));
CREATE TABLE HotelManagement.Reservation (
reservationID INT not null,
id_room INT not null,
guestEmail varchar(25) not null,
fromDate DATE not null,
toDate DATE not null,
PRIMARY KEY (reservationID),
FOREIGN KEY (guestEmail)
REFERENCES HotelManagement.Guest(email),
FOREIGN KEY (id_room)
REFERENCES HotelManagement.Room(roomID)
);
ALTER TABLE HotelManagement.Guest
ADD CONSTRAINT res_constr FOREIGN KEY (reservation)
REFERENCES HotelManagement.Reservation(reservationID);
Updated the .sql
In the hoteltask table you have already defined a foreign key named roomid. Foreign key names also have to be unique, so just give a different name to the 2nd foreign key or omit the name completely:
If the CONSTRAINT symbol clause is given, the symbol value, if used,
must be unique in the database. A duplicate symbol will result in an
error similar to: ERROR 1022 (2300): Can't write; duplicate key in
table '#sql- 464_1'. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, a name for the constraint
is created automatically.
UPDATE
The email field in the guest table is the rightmost column of the primary key, this way the pk cannot be used to independently look up email in that table. Either change the order or fields in the pk, or have a separate index on email field in the guest table. Quote from the same link as above:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Pls read through the entire documentation I linked before proceeding with creating the fks!
Side note 2 (1st is in the comments below): you should probably have a unique numeric guest id because that is lot more efficient than using email. Even if you decide to stick with email as id, I would restrict the pk in the guest table to email only. With the current pk I can register with the same email multiple times if I use different password.

MySQL - Error Code 1215, cannot add foreign key constraint

i got these two succesfull queries:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
and
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
but when i try this one:
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code),
foreign key(condition_code) references Donors_Medical_Condition(condition_code) );
i get "Error Code: 1215, cannot add foreign key constraint"
i dont know what am i doing wrong.
In MySql, a foreign key reference needs to reference to an index (including primary key), where the first part of the index matches the foreign key field. If you create an an index on condition_code or change the primary key st that condition_code is first you should be able to create the index.
To define a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES tbl_name (index_col_name,...)
Define an INDEX on condition_code in parent table Donors_Medical_Condition and it should be working.
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
KEY ( condition_code ), -- <---- this is newly added index key
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
But it seems you defined your tables order and references wrongly.
You should have defined foreign key in Donors_Medical_Condition table but not in Donors_Medical_Conditions table. The latter seems to be a parent.
Modify your script accordingly.
They should be written as:
-- create parent table first ( general practice )
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code)
);
-- child table of Medical_Conditions
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code)
references Donors_Medical_Condition(condition_code)
);
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
A workaround for those who need a quick how-to:
FYI: My issue was NOT caused by the inconsistency of the columns’ data types/sizes, collation or InnoDB storage engine.
How to:
Download a MySQL workbench and use it’s GUI to add foreign key. That’s it!
Why:
The error DOES have something to do with indexes. I learned this from the DML script automatically generated by the MySQL workbench. Which also helped me to rule out all those inconsistency possibilities.It applies to one of the conditions to which the foreign key definition subject. That is: “MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.” Here is the official statement: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
I did not get the idea of adding an index ON the foreign key column(in the child table), only paid attention to the referenced TO column(in the parent table).
Here is the auto-generated script(PHONE.PERSON_ID did not have index originally):
ALTER TABLE `netctoss`.`phone`
ADD INDEX `personfk_idx` (`PERSON_ID` ASC);
ALTER TABLE `netctoss`.`phone`
ADD CONSTRAINT `personfk`
FOREIGN KEY (`PERSON_ID`)
REFERENCES `netctoss`.`person` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I think you've got your tables a bit backwards. I'm assuming that Donors_Medical_Condtion links donors and medical conditions, so you want a foreign key for donors and conditions on that table.
UPDATED
Ok, you're also creating your tables in the wrong order. Here's the entire script:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code) );
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code) references Medical_Conditions(condition_code) );
I got the same issue and as per given answers, I verified all datatype and reference but every time I recreate my tables I get this error. After spending couple of hours I came to know below command which gave me inside of error-
SHOW ENGINE INNODB STATUS;
LATEST FOREIGN KEY ERROR
------------------------
2015-05-16 00:55:24 12af3b000 Error in foreign key constraint of table letmecall/lmc_service_result_ext:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT "fk_SERVICE_RESULT_EXT_LMC_SERVICE_RESULT1" FOREIGN KEY ("FK_SERVICE_RESULT") REFERENCES "LMC_SERVICE_RESULT" ("SERVICE_RESULT") ON DELETE NO ACTION ON UPDATE NO ACTION
I removed all relation using mysql workbench but still I see same error. After spending few more minutes, I execute below statement to see all constraint available in DB-
select * from information_schema.table_constraints where
constraint_schema = 'XXXXX'
I was wondering that I have removed all relationship using mysql workbench but still that constraint was there. And the reason was that because this constraint was already created in db.
Since it was my test DB So I dropped DB and when I recreate all table along with this table then it worked. So solution was that this constraint must be deleted from DB before creating new tables.
Check that both fields are the same size and if the referenced field is unsigned then the referencing field should also be unsigned.

Error Code: 1005 can't create table

please see my create statement:
CREATE TABLE INTERNAL_MEDICINE_DETAIL(DIAGNOSE_ITEM VARCHAR(15) NOT NULL,
EXM_RESULT VARCHAR(50),
IDENTIFY_ID INT AUTO_INCREMENT PRIMARY KEY,
SUMMARY_ID INT NOT NULL,
FOREIGN KEY(SUMMARY_ID) REFERENCES INTERNAL_MEDICINE_SUMMARY(SUMMARY_ID),
FOREIGN KEY(DIAGNOSE_ITEM) REFERENCES INTERNAL_MEDICINE_ITEM_DEF(DIAGNOSE_ITEM))
The referenced two tables are created successfully:
CREATE TABLE INTERNAL_MEDICINE_ITEM_DEF(DIAGNOSE_ITEM VARCHAR(15) NOT NULL,
ITEM_DESCRIPTION VARCHAR(50) NOT NULL,
IDENTIFY_ID INT AUTO_INCREMENT PRIMARY KEY)
CREATE TABLE INTERNAL_MEDICINE_SUMMARY(SUMMARY_ID INT AUTO_INCREMENT PRIMARY KEY,
SUMMARY VARCHAR(1000),
R_IDENTIFYID INT NOT NULL,
FOREIGN KEY(R_IDENTIFYID) REFERENCES BASICINFO(IDENTIFY_ID))
I have seen the mean of error code 1005 on MySQL web site, it says:
Cannot create table. If the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed. If the error message refers to error –1, table creation probably failed because the table includes a column name that matched the name of an internal InnoDB table.
my error is 150 currently, but I cannot find the difference of the two foreign keys defined in INTERNAL_MEDICINE_DETAIL table with the two fields defined in INTERNAL_MEDICINE_SUMMARY AND INTERNAL_MEDICINE_ITEM_DEF respectively.
So, could you please help me and tell me the reason?
From the InnoDB foreign key constraints documentation:
InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
You'll need to create an index on INTERNAL_MEDICINE_ITEM_DEF that has DIAGNOSE_ITEM as its first column. (No need to change anything for INTERNAL_MEDICINE_SUMMARY since the referenced column is that table's primary key.)