我使用了以下create语句:
CREATE TABLE `subscr` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`media_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY (`media_id`, `user_id`),
CONSTRAINT FOREIGN KEY (`media_id`) REFERENCES `media` (`id`) ON DELETE CASCADE,
CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB
为什么InnoDB只在user_id上放一个索引?我认为它需要所有外键引用的索引。
CREATE TABLE `subscr` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`media_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `media_id` (`media_id`,`user_id`),
KEY `user_id` (`user_id`),
CONSTRAINT `subscriptions_media_ibfk_1` FOREIGN KEY (`media_id`) REFERENCES `media` (`id`) ON DELETE CASCADE,
CONSTRAINT `subscriptions_media_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB
答案 0 :(得分:0)
media_id也有一个索引,它是唯一的。这对MySQL来说已经足够了。只有为user_id创建了一个单独的索引,因为唯一索引中的user_id是第二个,因此它对外键没用。