I have to create a database with two tables in MySQL, but the script fails with errno 150 (foreign key problem). I double-checked the foreign key fields to be the same on bo
While working with MySQL Workbench and MySQL 5.5.27, I have encountered the similar problem. In my case issue was with INT type fields. Erroneously in one table it was INT UNSIGNED and in referencing table it was INT.
table1.field1
has no index defined on it.
It is required to place a FOREIGN KEY
constraint on field1
.
With this:
CREATE TABLE IF NOT EXISTS `testdb`.`table1` (
`id` INT UNSIGNED NOT NULL ,
`field1` VARCHAR(50) NULL ,
KEY ix_table1_field1 (field1),
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
Everything should then work as expected.
Another hint:
Even when your data types seem to be the same - in my case both columns had VARCHAR(50)
- this is not enough.
You also need to make sure that both columns have the same COLLATION
.
For me, the problem was with using CONSTRAINT
in the CREATE TABLE
query.
MySQL will also throw this error if your mistyping the name of the referring table. I pulled my hair out for awhile until I realized I missed a letter in foreign key (column1) references mistyped_table(column1)
When I had this problem it was because I had set the id in the first table to be unsigned
whereas the foreign key in the second table was not. Making them both unsigned
fixed it for me.