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
Yet another cause, although slightly similar to others: I was referring to a table that turned out to have the MyISAM engine, instead of InnoDB.
In my case, one table was using foreign key constraints on another table that didn't exist yet. This was happening due to a large makefile, so it wasn't as obvious as I would've expected.
In case somebody is still having problems with this, I tried all the solutions above (except for SET FOREIGN_KEY_CHECKS) and nothing worked. The problem was that when you reference the first table, some databases are case sensitive about the table names. I think this is weird since I never saw this before on MySQL, Oracle and now this happened for me on MariaDB.
For example:
Create table if not exists CADASTRO_MAQUINAS ( Id VARCHAR(16), Primary Key (Id) );
Create table if not exists INFOS ( Id_Maquina VARCHAR(16) NOT NULL, CONSTRAINT FK_infos_cadastro_maquinas Foreign Key (Id_Maquina) references CADASTRO_MAQUINAS(Id) );
If I try to create the second table using cadastro_maquinas (lower cases) instead of CADASTRO_MAQUINAS, I will receive this error.
I got this error while trying to use a foreign key to reference a non-unique field. (which apparently is not allowed)
In very strange cases your database might be broken. In my case I did not have any foreign keys on the table and the only renaming the table or changing engine helped.
Turned out innoDB was broken, see: https://dba.stackexchange.com/questions/86853/1025-error-on-rename-of-table-errno-150-table-was-deleted-while-tried-to-a?lq=1
Always create master/parent tables first, and then create your detail/child tables.