优先使用单独索引,单独索引里有重复项时才用到联合索引
能用单独索引时,MySQL会认为没必要用到组合索引
https://bbs.csdn.net/topics/391036574?list=lz
我明白了,是不是因为我测试插入的10W条数据中,随机生成的gameCode字段值都不一样,所以mysql认为用gameCode索引就可以了,没必要用到组合索引,我试着把gameCode改为有重复的,就用到组合索引了
例子
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`course` varchar(50) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`) USING BTREE,
KEY `idx_course` (`course`) USING BTREE,
KEY `name_course_score` (`name`,`course`,`score`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO student(`name`, `course`, `score`) VALUES ('甲', '数学', '1');
EXPLAIN SELECT * FROM student WHERE `name`='甲' AND course='数学';
# 索引: idx_name
INSERT INTO student(`name`, `course`, `score`) VALUES ('甲', '语文', '1');
EXPLAIN SELECT * FROM student WHERE `name`='甲' AND course='数学';
# 索引: idx_course
INSERT INTO student(`name`, `course`, `score`) VALUES ('乙', '数学', '1');
EXPLAIN SELECT * FROM student WHERE `name`='甲' AND course='数学';
# 索引: name_course_score
网友评论