Foreign Key Constrain Fails with "Error creating foreign key on [table] (check data types)"

The data types need to match:

cities.id int(11)
hotels.city bigint(20)

Needs to become either:

cities.id bigint(20)
hotels.city bigint(20)

Or:

cities.id int(11)
hotels.city int(11)

Depending on what your application needs.

Also worth mentioning is the fact that both need to be either signed or unsigned.

You may need to OPTIMIZE your tables after changing the data types to match.


I know this is quite an old thread, but I spent some time with this error as well.

The situation I had was the following one:

Table 1: administrations (Primary key: AdministrationId) Table 2: invoices (Foreign key to AdministrationId) Table 3: users (error pops up while creating foreign key)

The colomns AdministrationId in my invoices and users table were both of the same type as the AdministrationId column in the administrations table.

The error on my side was that I tried to create a foreign key called administration_id in my users table. But a minute before that I already created a foreign key in my invoices table also called administration_id. When I tried to give the foreign key another name, it worked out fine.

Therefore, keep in mind to correctly name your foreign keys (e.g. prefix them with the table name, eg: invoices_administration_id and users_administration_id). Multiple foreign keys with the same name may not exist (within the same database).


I was using phpMyAdmin and i tried creating multiple indices on different tables using he relations view. However, I got the same error saying datatypes did not match. However, the cause indeed was that i was giving the same foreign key name to multiple relations, and because of duplicate names, mysql was throwing this error. So rename your relation, and it should work fine.

Foreign Key addition in relations view

Tags:

Mysql