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

Viewed 49893

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;
8 Answers

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'd like to point out, you will get a similar error in case you have set the foreign key to NOT NULL and you have set either the ON DELETE or ON UPDATE to SET NULL.

Udating data type cities.id bigint(20) and hotels.city bigint(20) OR Udating data type cities.id int(11) and hotels.city int(11) AND Updating hotels.city to unsigned because cities.id is unsigned.

Related