I
I
Ivan Torgov2018-02-14 11:08:36
MySQL
Ivan Torgov, 2018-02-14 11:08:36

Why remove the foreign key in order to remove the unique index?

I try to understand the issue, but I find only solutions to the issue, and not an explanation of why this is so.
There are 2 tables:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `number` int(10) unsigned NOT NULL,
  `title` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `user_id_number_unique` (`user_id`,`number`),
  CONSTRAINT `items_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

It is filled with data, everything is fine.
Suddenly I realized that I didn't need the number column in the items table.
To remove it, I first have to remove my composite unique index.
But for some reason MySQL doesn't let me do it just like that, without dancing with a tambourine.
I enter a query: What I get is the error Cannot drop index 'user_id_number_unique': needed in a foreign key constraint . And I have to first remove the foreign key (which I have is items_ibfk_1 from the example above), remove the user_id_number_unique index, remove the number field, and return the foreign key again. I can't figure out what's wrong with the foreign key?
DROP INDEX user_id_number_unique ON items;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-02-14
@itorgov

A foreign key must have an index, otherwise it cannot be created. If there is no index, it is created automatically when the foreign key is created, so it may seem that there is no relationship between them.

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist . This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
https://dev.mysql.com/doc/refman/5.7/en/create-tab...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question