MySQL组合索引的一个小问题

现在有几个sql查询语句,分别对表中的a,b,c字段进行查询,有如下语句:

  • where a=x and b=x and c=x
  • where a=x and c=x
  • where a=x and b=x

这个时候你要怎么建立索引呢?

我们都知道,MySQL的组合索引是有顺序的,必须要遵循顺序才能让索引生效。那么上面语句的只用其中两个字段会用到组合索引吗?

实际上是用的到的,建立索引应该建立(a,b,c)的

测试:

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(200) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `a` int(11) DEFAULT NULL,
  `b` int(11) DEFAULT NULL,
  `c` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `inx_a_b_c` (`a`,`b`,`c`)
) ENGINE=InnoDB AUTO_INCREMENT=1111 DEFAULT CHARSET=utf8;

插入数据:

INSERT INTO `user` (`id`, `name`, `age`, `a`, `b`, `c`)
VALUES
    (1, 'aihe', 10, 1, 8, 11),
    (2, 'aihe', 10, 2, 7, 12),
    (4, 'aihe', 10, 3, 6, 13),
    (5, 'aihe', 10, 4, 5, 14),
    (25, 'ac', 10, 5, 4, 15),
    (26, 'ac', 10, 6, 3, 16),
    (28, 'ac', 10, 7, 2, 17),
    (31, 'ac', 10, 8, 1, 18);

分别进行explain:

//肯定可以,大家都知道
EXPLAIN select * from user where a=1 and b=2 and c=3;
// 也是正常的
EXPLAIN select * from user where a=1 and b=2;
// 也能用到索引,如果没有遇到条件比较的话,还是会继续往下走 type=ref
EXPLAIN select * from user where a=1 and c=3;
// type=range
EXPLAIN select * from user where a=1 and b > 5 and c=3;
// type =range
EXPLAIN select * from user where a=1 and b = 5 and c>3;

// type =const
EXPLAIN select * from user where a=1 and c>3;

// type=all,用不到索引
EXPLAIN select * from user where b = 5;
//用不到索引
EXPLAIN select * from user where b = 5 and c=10;

如果只是用=进行查询的话,添加组合索引一般都能用的到。

这是一个不太确定的知识点,进行验证下。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容