Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

The following query fails with error "Error creating foreign key on city (check data types)":

ALTER TABLE  `hotels` ADD FOREIGN KEY (  `city` )
REFERENCES  `mydatabase`.`cities` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE ;

Basically I want to have a ony-to-many relation between city.id and hotels.city.

Here are both tables:

CREATE TABLE IF NOT EXISTS `cities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;


CREATE TABLE IF NOT EXISTS `hotels` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `city` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `city` (`city`)
) ENGINE=InnoDB;
like image 698
Dzhuneyt Avatar asked Aug 12 '12 22:08

Dzhuneyt


3 Answers

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.

like image 60
Mihai Stancu Avatar answered Nov 08 '22 03:11

Mihai Stancu


I was using phpMyAdmin and i tried creating multiple indices on different tables using the 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

like image 15
Yogesh Kumar Gupta Avatar answered Nov 08 '22 03:11

Yogesh Kumar Gupta


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

like image 13
Roy Lenferink Avatar answered Nov 08 '22 01:11

Roy Lenferink