mysql组合索引前导列

一、什么是组合索引前导列?

CREATE TABLE `test_user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `update_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  KEY `index` (`name`,`age`,`create_date`,`update_date`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8

   前导列:复合索引第一列或者连续多列(多列的顺序不影响);

        如上图例如(【name】,【name,age】,【age,name】,【name,age,create_date】)这种属于前导列;

       (【age,create_date】,【create_date】)这种不属于;

1、where子句中,前导列必须使用等于或者in操作,最右边的列可以使用不等式,这样索引才可以完全生效。同时,where子句中的列不需要全建立了索引,但是必须保证建立索引的列之间没有间隙

 (1)where name='bray' and age in(11,25) and create_date='2020-11-01 00:00:00' and update_date='2020-11-01 00:00:00'           这种情况索引都是生效的

  (2)where name='bray' and age in(11,25) and create_date>'2020-11-01 00:00:00' and update_date='2020-11-01 00:00:00'   
         那这里只有name,age 和create_date的索引会是有效的,update_date列的索引会失效,因为它在create_date列的右边,而create_date列使用了不等式,根据使用不等式的限制,create_date列已经属于最右边。

     (3)where  age in(11,25) and create_date='2020-11-01 00:00:00' and update_date='2020-11-01 00:00:00'   
       索引将不会被使用,因为没有使用前导列,不是从name列开始,这个查询会是一个全表查询。

你可能感兴趣的:(sql)