Error Code: 1005 can't create table - mysql

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

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.

unable to set foreign key 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.)

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.

Unable to add two foreign keys to a table

I have two tables as follow:
1st Table:
CREATE TABLE User (
User_ID VARCHAR(8)NOT NULL PRIMARY KEY,
User_Name VARCHAR (25) NOT NULL,
User_Gender CHAR (1) NOT NULL,
User_Position VARCHAR (10) NOT NULL,
);
2nd table:
CREATE TABLE Training (
Training_Code VARCHAR(8) NOT NULL Primary Key,
Training_Title VARCHAR(30) NOT NULL,
);
I am trying to create a table which has two foreign keys to join both of the previous tables:
CREATE TABLE Request (
User_ID VARCHAR(8) NOT NULL,
Training_Code VARCHAR(8) NOT NULL,
Request_Status INT(1) NOT NULL
);
When I am trying to set the foreign keys in the new table, the User_ID can be done successfully but the Training_Code cannot be set to foreign key due to the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
As I searched for this problem, the reason for it, is that data type is not the same, or name is not the same.. but in my situation both are correct so could you tell me what is wrong here ?
You need an index for this column in table Request too:
Issue first
CREATE INDEX idx_training_code ON Request (Training_Code);
Then you should be successful creating the foreign key constraint with
ALTER TABLE Request
ADD CONSTRAINT FOREIGN KEY idx_training_code (Training_Code)
REFERENCES Training(Training_Code);
It worked for me. But I've got to say that it worked without create index too, as the documentation of Using FOREIGN KEY Constraints states:
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.
Emphasis by me. I don't know what's the issue in your case.
Demo
Explanation of the issue
The behavior mentioned in the question can be reproduced if the table Training is using the MyISAM storage engine. Then creating a foreign key referencing the table Training will produce the mentioned error.
If there's data in the table, then simple dropping of the table would not be the best solution. You can change the storage engine to InnoDB with
ALTER TABLE Training Engine=InnoDB;
Now you can successfully add the foreign key constraint.

Foreign key error when creating table (errno 150)

I'm trying to create a relationship between two tables using the following queries:
create table card
(id int not null auto_increment,
post_id bigint(20) unsigned not null,
primary key(id));
create table user_comment
(id int not null auto_increment,
comment_author longtext,
comment_post_id bigint(20) unsigned not null,
primary key (id),
foreign key (comment_post_id) references card(post_id));
However it gives me the following error message:
ERROR 1005 (HY000) at line 9: Can't create table 'test.user_comment'
(errno: 150)
If I execute the command for showing innodb status:
show engine innodb status;
It shows this message:
LATEST FOREIGN KEY ERROR
Error in foreign key constraint of table test/user_comment: foreign key
(comment_post_id) references card(post_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.
But I still can't figure out how to fix the problem.
Any ideas?
From the docs:
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.
Create an index on card (post_id).
Just use this command once before creating the table:
SET FOREIGN_KEY_CHECKS=0;