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;

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

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

你可能感兴趣的:(MySQL组合索引的一个小问题)