Serhioromano
@Serhioromano
Web Developer

Нужно ли создавать индекс на поле внешней ссылки?

Допустим у меня 2 таблицы

CREATE TABLE `wr3_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


И таблица значений

CREATE TABLE `wr3_user_option` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL DEFAULT '0',
  `name` varchar(45) NOT NULL,
  `val` varchar(45) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `wr3_user_option_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `wr3_user` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


Нужно ли здесь KEY `user_id` (`user_id`), или внешняя ссылка уже является ключем?
  • Вопрос задан
  • 56 просмотров
Пригласить эксперта
Ответы на вопрос 1
alexey-m-ukolov
@alexey-m-ukolov Куратор тега MySQL
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...
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы