Related
I'm having some problems creating a foreign key to an existing table in a MySQL database.
I have the table exp:
+-------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| EID | varchar(45) | NO | PRI | NULL | |
| Comment | text | YES | | NULL | |
| Initials | varchar(255) | NO | | NULL | |
| ExpDate | date | NO | | NULL | |
| InsertDate | date | NO | | NULL | |
| inserted_by | int(11) unsigned | YES | MUL | NULL | |
+-------------+------------------+------+-----+---------+-------+
and I wan't to create a new table called sample_df referencing this, using the following:
CREATE TABLE sample_df (
df_id mediumint(5) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sample_type mediumint(5) UNSIGNED NOT NULL,
df_10 boolean NOT NULL,
df_100 boolean NOT NULL,
df_1000 boolean NOT NULL,
df_above_1000 boolean NOT NULL,
target int(11) UNSIGNED NOT NULL,
assay mediumint(5) UNSIGNED ZEROFILL NOT NULL,
insert_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
inserted_by int(11) UNSIGNED NOT NULL,
initials varchar(255),
experiment varchar(45),
CONSTRAINT FOREIGN KEY (inserted_by) REFERENCES user (iduser),
CONSTRAINT FOREIGN KEY (target) REFERENCES protein (PID),
CONSTRAINT FOREIGN KEY (sample_type) REFERENCES sample_type (ID),
CONSTRAINT FOREIGN KEY (assay) REFERENCES assays (AID),
CONSTRAINT FOREIGN KEY (experiment) REFERENCES exp (EID)
);
But I get the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
To get some more information, I did:
SHOW ENGINE INNODB STATUS\G
From which I got:
FOREIGN KEY (experiment) REFERENCES exp (EID)
):
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.
To me, the column types seem to match, since they are both varchar(45). (I also tried setting the experiment column to not null, but this didn't fix it). So I guess the problem must be that
Cannot find an index in the referenced table where the referenced columns appear as the first columns.
But I'm not quite sure what this means, or how to check/fix it. Does anyone have any suggestions? And what is meant by first columns?
Just throwing this into the mix of possible causes, I ran into this when the referencing table column had the same "type" but did not have the same signing.
In my case, the referenced table colum was TINYINT UNSIGNED and my referencing table column was TINYINT SIGNED. Aligning both columns solved the issue.
This error can also occur, if the references table and the current table don't have the same character set.
According to http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html
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.
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.
So if the index in referenced table is exist and it is consists from several columns, and desired column is not first, the error shall be occurred.
The cause of our error was due to violation of following rule:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation
must be the same.
As mentioned #Anton, this could be because of the different data type.
In my case I had primary key BIGINT(20) and tried to set foreight key with INT(10)
Mine was a collation issue between the referenced table and the to be created table so I had to explicitly set the collation type of the key I was referencing.
First I ran a query at referenced table to get its collation type
show table STATUS like '<table_name_here>';
Then I copied the collation type and explicitly stated employee_id's collation type at the creation query. In my case it was utf8_general_ci
CREATE TABLE dbo.sample_db
(
id INT PRIMARY KEY AUTO_INCREMENT,
event_id INT SIGNED NOT NULL,
employee_id varchar(45) COLLATE utf8_general_ci NOT NULL,
event_date_time DATETIME,
CONSTRAINT sample_db_event_event_id_fk FOREIGN KEY (event_id) REFERENCES event (event_id),
CONSTRAINT sample_db_employee_employee_id_fk FOREIGN KEY (employee_id) REFERENCES employee (employee_id)
);
In my case, it turned out the referenced column wasn't declared primary or unique.
https://stackoverflow.com/a/18435114/1763217
For me it was just the charset and collation of the DB. I changed to utf8_unicode_ci and works
In my case, it was an incompatibility with ENGINE and COLLATE, once i added ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci it worked
CREATE TABLE `some_table` (
`id` varchar(36) NOT NULL,
`col_id` varchar(36) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_some_table_cols_col_id` FOREIGN KEY (`col_id`) REFERENCES `ref_table` (`id`) ON DELETE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The exact order of the primary key also needs to match with no extra columns in between.
I had a primary key setup where the column order actually matches, but the problem was the primary key had an extra column in it that is not part of the foreign key of the referencing table
e.g.) table 2, column (a, b, c) -> table 1, column (a, b, d, c) -- THIS FAILS
I had to reorder the primary key columns so that not only they're ordered the same way, but have no extra columns in the middle:
e.g.) table 2, column (a, b, c) -> table 1, column (a, b, c, d) -- THIS SUCCEEDS
I had this error as well. None of the answers pertained to me. In my case, my GUI automatically creates a table with a primary unique identifier as "unassigned". This fails when I try and create a foreign key and gives me the exact same error. My primary key needs to be assigned.
If you write the SQL itself like so id int unique auto_increment then you don't have this issue but for some reason my GUI does this instead id int unassigned unique auto_increment.
Hope this helps someone else down the road.
In my case was created using integer for the id, and the referencing table was creating by default a foreign key using bigint.
This caused a big nightmare in my Rails app as the migration failed but the fields were actually created in DB, so they showed up in the DB but not in the schema of the Rails app.
Referencing the same column more than once in the same constraint also produces this Cannot find an index in the referenced table error, but can be difficult to spot on large tables. Split up the constraints and it will work as expected.
In some cases, I had to make the referenced field unique on top of defining it as the primary key.
But I found that not defining it as unique doesn't create a problem in every case. I have not been able to figure out the scenarios though. Probably something to do with nullable definition.
Just to throw another solution in the mix. I had on delete set to set null but the field that i was putting the foreign key on was NOT nullable so making it nullable allowed the foreign key to be created.
As others have said the following things can be an issue
Field Length - INT -> BIGINT, VARCHAR(20) -> VARCHAR(40)
Unsigned - UNSIGNED -> Signed
Mixed Collations
And just to add to this , I've had the same issue today
Both fields were int of same length etc, however, one was unsigned and this was enough to break it.
Both needed to be declared as unsigned
I had the same problem with writing this piece of code in the OnModelCreating method
My problem was completely solved and my tables and migrations were created without errors. Please try it
var cascadeFKs = modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetForeignKeys())
.Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);
foreach (var fk in cascadeFKs)
fk.DeleteBehavior = DeleteBehavior.Restrict;
It is mostly because the old table you are referring to does not have the suitable data type / collation / engine with the new table. The way to detect the difference is dumping that old table out and see how the database collect the information to have the dump script
mysqldump -uroot -p -h127.0.0.1 your_database your_old_table > dump_table.sql
It will give you enough information for you to compare
create table your_old_table
(
`id` varchar(32) not null,
) Engine = InnoDB DEFAULT CHARSET=utf8mb3;
This only works if you have the permission to dump your table scheme
I spent hours trying to get this to work. It turned out I had an older version of Heidi, 11.0.0.5919 which was not displaying the UNSIGNED attribute in the create table statement (Heidi bug), which I had used to copy from. Couldn't see it in the table design view either.
So the original table had an UNSIGNED attribute, but my foreign key didn't. The solution was upgrading Heidi, and adding the UNSIGNED attribute in the create table .
CREATE TABLE `extension` (
`ExtensionId` INT NOT NULL,
`AccountId` INT NOT NULL,
PRIMARY KEY (`ExtensionId`) USING BTREE,
INDEX `AccountId` (`AccountId`) USING BTREE,
CONSTRAINT `AccountId` FOREIGN KEY (`AccountId`) REFERENCES `accounts` (`AccountId`) ON UPDATE NO ACTION ON DELETE NO ACTION,
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
;
Change to:
`AccountId` INT UNSIGNED NOT NULL,
If Data type is same, Probably error is due to different Charset and Collation, try altering column as referenced column's Character set and Collate with a query something like this,
ALTER TABLE table_name MODIFY COLUMN
column_name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci;
and then run the query for foreign key..
(alter charset of a table and database didn't work for me on incompatible error, until I alter specific column like my above suggestion)
In my case I referred directly to a PRIMARY KEY and got the error shown above. After adding a "normal" index additionally to my primary key it worked:
ALTER TABLE `TableName` ADD INDEX `id` (`id`);
Now it looks like this:
When I try to drop the INDEX id again I get following error:
(1553): Cannot drop index 'id': needed in a foreign key constraint.
EDIT:
This is not a new question - I just want to show the way i solved this problem for me and what kind of problems may occur.
i got a problem adding a foreign key in mysql (using phpmyadmin).
ALTER TABLE `production_x_country` ADD FOREIGN KEY (`country`) REFERENCES `pmdb_0.3.12`.`countries`(`iso_3166_1`) ON DELETE CASCADE ON UPDATE CASCADE;
#1215 - Cannot add foreign key constraint
based on some research and tests i've come to the conclusion that CHAR (that production_x_country.country field) is no valid foreign key field type - though i did not find any hint to that assumption in the mysql docs.
if i change the column type to some other character type like VARCHAR, the procedure works.
a similar question was "solved" here, but that linked answer wasn't about the type-problem but about a country code being a primary key (what makes perfect sense to me): https://stackoverflow.com/a/1419235/4302731
table descriptions:
CREATE TABLE IF NOT EXISTS `countries` (
`iso_3166_1` char(3) NOT NULL, <----- primary key to be referenced to
`name` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `countries` ADD PRIMARY KEY (`iso_3166_1`);
CREATE TABLE IF NOT EXISTS `production_x_country` (
`production` int(11) NOT NULL,
`country` char(3) CHARACTER SET utf8 NOT NULL <----- column that should hold the foreign key
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
is there any solution (yes, i could go on using varchar, but thats not satisfying to me)? and most important: is there any explanation?
thank you for your help!
solved - see my own answer below
solved!
this is not about the char field type but about the collation!
i like using UTF-8 mostly utf8_bin. so did i with the collation of my primary key:
`iso_3166_1` char(3) CHARACTER SET utf8
once i changed the primary key's collation to "latin1_swedish_ci" the foreign key application worked.
leads to the question: why is the collation of the primary key field (maybe also the foreign key field's, haven't checked that yet) important?
I'm having some problems creating a foreign key to an existing table in a MySQL database.
I have the table exp:
+-------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| EID | varchar(45) | NO | PRI | NULL | |
| Comment | text | YES | | NULL | |
| Initials | varchar(255) | NO | | NULL | |
| ExpDate | date | NO | | NULL | |
| InsertDate | date | NO | | NULL | |
| inserted_by | int(11) unsigned | YES | MUL | NULL | |
+-------------+------------------+------+-----+---------+-------+
and I wan't to create a new table called sample_df referencing this, using the following:
CREATE TABLE sample_df (
df_id mediumint(5) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
sample_type mediumint(5) UNSIGNED NOT NULL,
df_10 boolean NOT NULL,
df_100 boolean NOT NULL,
df_1000 boolean NOT NULL,
df_above_1000 boolean NOT NULL,
target int(11) UNSIGNED NOT NULL,
assay mediumint(5) UNSIGNED ZEROFILL NOT NULL,
insert_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
inserted_by int(11) UNSIGNED NOT NULL,
initials varchar(255),
experiment varchar(45),
CONSTRAINT FOREIGN KEY (inserted_by) REFERENCES user (iduser),
CONSTRAINT FOREIGN KEY (target) REFERENCES protein (PID),
CONSTRAINT FOREIGN KEY (sample_type) REFERENCES sample_type (ID),
CONSTRAINT FOREIGN KEY (assay) REFERENCES assays (AID),
CONSTRAINT FOREIGN KEY (experiment) REFERENCES exp (EID)
);
But I get the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
To get some more information, I did:
SHOW ENGINE INNODB STATUS\G
From which I got:
FOREIGN KEY (experiment) REFERENCES exp (EID)
):
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.
To me, the column types seem to match, since they are both varchar(45). (I also tried setting the experiment column to not null, but this didn't fix it). So I guess the problem must be that
Cannot find an index in the referenced table where the referenced columns appear as the first columns.
But I'm not quite sure what this means, or how to check/fix it. Does anyone have any suggestions? And what is meant by first columns?
Just throwing this into the mix of possible causes, I ran into this when the referencing table column had the same "type" but did not have the same signing.
In my case, the referenced table colum was TINYINT UNSIGNED and my referencing table column was TINYINT SIGNED. Aligning both columns solved the issue.
This error can also occur, if the references table and the current table don't have the same character set.
According to http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html
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.
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.
So if the index in referenced table is exist and it is consists from several columns, and desired column is not first, the error shall be occurred.
The cause of our error was due to violation of following rule:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation
must be the same.
As mentioned #Anton, this could be because of the different data type.
In my case I had primary key BIGINT(20) and tried to set foreight key with INT(10)
Mine was a collation issue between the referenced table and the to be created table so I had to explicitly set the collation type of the key I was referencing.
First I ran a query at referenced table to get its collation type
show table STATUS like '<table_name_here>';
Then I copied the collation type and explicitly stated employee_id's collation type at the creation query. In my case it was utf8_general_ci
CREATE TABLE dbo.sample_db
(
id INT PRIMARY KEY AUTO_INCREMENT,
event_id INT SIGNED NOT NULL,
employee_id varchar(45) COLLATE utf8_general_ci NOT NULL,
event_date_time DATETIME,
CONSTRAINT sample_db_event_event_id_fk FOREIGN KEY (event_id) REFERENCES event (event_id),
CONSTRAINT sample_db_employee_employee_id_fk FOREIGN KEY (employee_id) REFERENCES employee (employee_id)
);
In my case, it turned out the referenced column wasn't declared primary or unique.
https://stackoverflow.com/a/18435114/1763217
For me it was just the charset and collation of the DB. I changed to utf8_unicode_ci and works
In my case, it was an incompatibility with ENGINE and COLLATE, once i added ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci it worked
CREATE TABLE `some_table` (
`id` varchar(36) NOT NULL,
`col_id` varchar(36) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_some_table_cols_col_id` FOREIGN KEY (`col_id`) REFERENCES `ref_table` (`id`) ON DELETE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
The exact order of the primary key also needs to match with no extra columns in between.
I had a primary key setup where the column order actually matches, but the problem was the primary key had an extra column in it that is not part of the foreign key of the referencing table
e.g.) table 2, column (a, b, c) -> table 1, column (a, b, d, c) -- THIS FAILS
I had to reorder the primary key columns so that not only they're ordered the same way, but have no extra columns in the middle:
e.g.) table 2, column (a, b, c) -> table 1, column (a, b, c, d) -- THIS SUCCEEDS
I had this error as well. None of the answers pertained to me. In my case, my GUI automatically creates a table with a primary unique identifier as "unassigned". This fails when I try and create a foreign key and gives me the exact same error. My primary key needs to be assigned.
If you write the SQL itself like so id int unique auto_increment then you don't have this issue but for some reason my GUI does this instead id int unassigned unique auto_increment.
Hope this helps someone else down the road.
In my case was created using integer for the id, and the referencing table was creating by default a foreign key using bigint.
This caused a big nightmare in my Rails app as the migration failed but the fields were actually created in DB, so they showed up in the DB but not in the schema of the Rails app.
Referencing the same column more than once in the same constraint also produces this Cannot find an index in the referenced table error, but can be difficult to spot on large tables. Split up the constraints and it will work as expected.
In some cases, I had to make the referenced field unique on top of defining it as the primary key.
But I found that not defining it as unique doesn't create a problem in every case. I have not been able to figure out the scenarios though. Probably something to do with nullable definition.
Just to throw another solution in the mix. I had on delete set to set null but the field that i was putting the foreign key on was NOT nullable so making it nullable allowed the foreign key to be created.
As others have said the following things can be an issue
Field Length - INT -> BIGINT, VARCHAR(20) -> VARCHAR(40)
Unsigned - UNSIGNED -> Signed
Mixed Collations
And just to add to this , I've had the same issue today
Both fields were int of same length etc, however, one was unsigned and this was enough to break it.
Both needed to be declared as unsigned
I had the same problem with writing this piece of code in the OnModelCreating method
My problem was completely solved and my tables and migrations were created without errors. Please try it
var cascadeFKs = modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetForeignKeys())
.Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);
foreach (var fk in cascadeFKs)
fk.DeleteBehavior = DeleteBehavior.Restrict;
It is mostly because the old table you are referring to does not have the suitable data type / collation / engine with the new table. The way to detect the difference is dumping that old table out and see how the database collect the information to have the dump script
mysqldump -uroot -p -h127.0.0.1 your_database your_old_table > dump_table.sql
It will give you enough information for you to compare
create table your_old_table
(
`id` varchar(32) not null,
) Engine = InnoDB DEFAULT CHARSET=utf8mb3;
This only works if you have the permission to dump your table scheme
I spent hours trying to get this to work. It turned out I had an older version of Heidi, 11.0.0.5919 which was not displaying the UNSIGNED attribute in the create table statement (Heidi bug), which I had used to copy from. Couldn't see it in the table design view either.
So the original table had an UNSIGNED attribute, but my foreign key didn't. The solution was upgrading Heidi, and adding the UNSIGNED attribute in the create table .
CREATE TABLE `extension` (
`ExtensionId` INT NOT NULL,
`AccountId` INT NOT NULL,
PRIMARY KEY (`ExtensionId`) USING BTREE,
INDEX `AccountId` (`AccountId`) USING BTREE,
CONSTRAINT `AccountId` FOREIGN KEY (`AccountId`) REFERENCES `accounts` (`AccountId`) ON UPDATE NO ACTION ON DELETE NO ACTION,
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
;
Change to:
`AccountId` INT UNSIGNED NOT NULL,
If Data type is same, Probably error is due to different Charset and Collation, try altering column as referenced column's Character set and Collate with a query something like this,
ALTER TABLE table_name MODIFY COLUMN
column_name VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci;
and then run the query for foreign key..
(alter charset of a table and database didn't work for me on incompatible error, until I alter specific column like my above suggestion)
In my case I referred directly to a PRIMARY KEY and got the error shown above. After adding a "normal" index additionally to my primary key it worked:
ALTER TABLE `TableName` ADD INDEX `id` (`id`);
Now it looks like this:
When I try to drop the INDEX id again I get following error:
(1553): Cannot drop index 'id': needed in a foreign key constraint.
EDIT:
This is not a new question - I just want to show the way i solved this problem for me and what kind of problems may occur.
This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 9 years ago.
I am using MySQL 5 to try and create two tables. Here are the two tables:
DROP TABLE IF EXISTS `users` ;
CREATE TABLE IF NOT EXISTS `users` (
`username` VARCHAR(50) not null ,
`password` VARCHAR(50) not null,
`enabled` boolean not null,
`accountNonExpired` boolean not null,
`accountNonLocked` boolean not null,
`credentialsNonExpired` boolean not null,
PRIMARY KEY (`username`)
) ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
DROP TABLE IF EXISTS `authorities` ;
create table IF NOT EXISTS `authorities` (
`username` VARCHAR(50) not null ,
`authority` varchar(50) not null,
foreign key (`username`) references `users` (`username`),
unique index authorities_idx_1 (username, authority)
) engine = InnoDb;
When I try to execute this statement, the users table is created but then I get the error:
Error Code: 1005
Can't create table 'dental.authorities' (errno: 150)
I am not seeing why this foreign key fails when the two referenced columns are identical. Is there
Foreign keys require both keys to have the same character set.
Add
DEFAULT CHARACTER SET = utf8;
to your second table CREATE instruction.
Edit: Oh boy looks like I'm late to the party.
Depending on your server version and settings, you might need to add
DEFAULT CHARACTER SET = utf8
to the CREATE TABLE statement for "authorities". That will match the character set of the referenced table.
check out following points:
i think DEFAULT CHARACTER SET = utf8; not provided to second table
1. The two tables must be ENGINE=InnoDB. (can be others: ENGINE=MyISAM
works too)
2. The two tables must have the same charset.
3. The PK column(s) in the parent table and the FK column(s) must be
the same data type.
4. 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;
5. If there is data already in the foreign key table, the FK column
value(s) must match values in the parent table PK columns.
6. And the child table cannot be a temporary table.
Hope this helps.
I'm creating a few simple tables and I can't get passed this foreign key error and I'm not sure why. Here's the script below.
create TABLE Instructors (
ID varchar(10),
First_Name varchar(50) NOT NULL,
Last_Name varchar(50) NOT NULL,
PRIMARY KEY (ID)
);
create table Courses (
Course_Code varchar(10),
Title varchar(50) NOT NULL,
PRIMARY KEY (Course_Code)
);
create table Sections (
Index_No int,
Course_Code varchar(10),
Instructor_ID varchar(10),
PRIMARY KEY (Index_No),
FOREIGN KEY (Course_Code) REFERENCES Courses(Course_Code)
ON DELETE cascade
ON UPDATE cascade,
FOREIGN KEY (Instructor_ID) REFERENCES Instructors(ID)
ON DELETE set default
);
Error Code: 1005. Can't create table '336_project.sections' (errno: 150)
My data types seem identical and the syntax seems correct. Can anyone point out what I'm not seeing here?
I'm using MySQL Workbench 5.2
This error also occurs if you are relating columns of different types, eg. int in the source table and BigInt in the destination table.
If you're using the InnoDB engine, the ON DELETE SET DEFAULT is your problem. Here's an excerpt from the manual:
While SET DEFAULT is allowed by the MySQL Server, it is rejected as invalid by InnoDB. CREATE TABLE and ALTER TABLE statements using this clause are not allowed for InnoDB tables.
You can use ON DELETE CASCADE or ON DELETE SET NULL, but not ON DELETE SET DEFAULT. There's more information here.
You can run
SHOW ENGINE INNODB STATUS
to read the reason of the failure in a human readable format
e.g.
------------------------
LATEST FOREIGN KEY ERROR
------------------------
150331 15:51:01 Error in foreign key constraint of table foobar/#sql-413_81:
FOREIGN KEY (`user_id`) REFERENCES `foobar`.`users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE:
You have defined a SET NULL condition though some of the columns are defined as NOT NULL.
In order to create a FOREIGN KEY with reference to another table, the keys from both tables should be PRIMARY KEY and with the same datatype.
In your table sections, PRIMARY KEY is of different datatype i.e INT but in another table, it's of type i.e VARCHAR.
It may also be the case if you are not specifying the ON DELETE at all but are trying to reference a MYISAM table from InnoDB table:
CREATE TABLE `table1`(
`id` INT UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MYISAM CHARACTER SET UTF8;
CREATE TABLE `table2`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`table1_id` INT UNSIGNED NOT NULL,
`some_value` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_table1_id`(`table1_id`),
CONSTRAINT FOREIGN KEY (`table1_id`) REFERENCES `table1`(`id`)
) ENGINE=INNODB CHARACTER SET UTF8;
The above will throw errno 150. One need to change the first table to InnoDB too for this to work.
It is failing on the
ON DELETE set default
I have not come across that before and I am not seeing it in the manuals either ( but then it is late )
Update
just seen this in the manual
While SET DEFAULT is allowed by the MySQL Server, it is rejected as
invalid by InnoDB. CREATE TABLE and ALTER TABLE statements using this
clause are not allowed for InnoDB tables.
I guess you may be using InnoDB tables ?
For completeness sake - you will also get this error if you make a foreign reference to a table that isn't defined at the time;
Here Problem is in database engine ( table1 MYISAM and table2 ENGINE).
To set FOREIGN KEYs,
Both table must be in same ENGINE and same charset.
PK column in parent and FK column must be in same data type and same collation type.
Hope you got an idea.
Make sure that table type is InnoDB, MyISAM does not support foreign key, afaik.