a、
b和
c,这三个字段建立一个联合索引,使用
where b = ? and c = ?的查询条件,是否会走到索引。
创建模拟表
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`age` int(11) DEFAULT '0',
`sex` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `a` (`name`,`age`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
BEGIN;
INSERT INTO `user` (`id`, `name`, `age`, `sex`) VALUES (1, '1', 0, 1);
INSERT INTO `user` (`id`, `name`, `age`, `sex`) VALUES (2, '1', 0, 1);
INSERT INTO `user` (`id`, `name`, `age`, `sex`) VALUES (3, '1', 0, 1);
INSERT INTO `user` (`id`, `name`, `age`, `sex`) VALUES (4, '1', 0, 1);
INSERT INTO `user` (`id`, `name`, `age`, `sex`) VALUES (5, '2', 0, 1);
COMMIT;
测试查询
explain打印结果查看一下。
explain select * from `user`;
explain执行结果。
***************************[ 1. row ]***************************
id | 1
select_type | SIMPLE
table | user
partitions | <null>
type | ALL
possible_keys | <null>
key | <null>
key_len | <null>
ref | <null>
rows | 5
filtered | 100.0
Extra | <null>
id和
(name, age)都有建立索引,但是
select * from user
语句中的 "*" 要求查询到age
字段,age` 字段在既没有建立索引,也没有在索引树上。要查询该字段,还需要进行全表扫描。
where条件字段查询
explain select id,age from `user` where age = 0;
explain语句打印一下执行结果。
***************************[ 1. row ]***************************
id | 1
select_type | SIMPLE
table | user
partitions | <null>
type | index
possible_keys | a
key | a
key_len | 1027
ref | <null>
rows | 5
filtered | 20.0
Extra | Using where; Using index
type字段,可以很明显的看到,使用了
index类型的查询。
index 字段说明
index字段,有这样一段说明。
index类型的查询与
ALL查询是相同,不同之处在于
扫描索引树,也就是说,还是走到了索引,只不过是全盘扫描索引树,然后在进行磁盘查找。
ALL查询效果高,这是因为直接在索引树中就查询到数据了。
总结
type类型,并不是完全不走索引的,如果
type字段是
ALL则走的全表扫描;如果是
index则会进行索引树扫描,然后再全盘扫描,这种情况仍然是走到索引了。

文章转载自卡二条的技术圈,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




