Answer the question
In order to leave comments, you need to log in
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;
DROP INDEX user_id_number_unique ON items;
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question