如何理解并正确使用MySql索引(3)

概述
索引是存储引擎用于快速查找记录的一种数据结构,通过合理的使用数据库索引可以大大提高系统的访问性能,接下来主要介绍在MySQL数据库中索引类型,以及如何创建出更加合理且高效的索引技巧。
** 这里主要针对的是InnoDB存储引擎的B+Tree索引数据结构。**

1、索引的优点

  • 大大减轻了服务器需要扫描的数据量,从而提高了数据的检索速度
  • 帮助服务器避免排序和临时表
  • 可以将随机I/O变为顺序I/O

2、索引的创建

2.1 主键索引

alter table 'table_name' add primary key 'index_name' ('column');

2.2 唯一索引

alter table 'table_name' add unique 'index_name' ('column');

2.3 普通索引

alter table 'table_name' add index 'index_name' ('column');

2.4 全文索引

alter table 'table_name' add fulltext 'index_name' ('column');

2.5 组合索引

alter table 'table_name' add index 'index_name' ('column1','column2');

3、B+Tree的索引规则

创建一个测试的用户表:
create table user_test(id int AUTO_INCREMENT PRIMARY KEY, user_name varchar(30) NOT NULL, sex bit(1) NOT NULL DEFAULT b'1', city varchar(50) NOT NULL, age int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;

如何理解并正确使用MySql索引(3)_第1张图片
mysql_index01.png

创建一个组合索引:
alter table user_test add index idx_user(user_name,city,age);

mysql_index02.png
3.1 索引有效的查询
3.1.1全值匹配

全值匹配值指的是和索引中的所有列进行匹配,如:以上面创建的索引为例,在where条件后可以同时查询(user_name,city,age)为条件的数据。
注:与where后面查询条件的顺序无关,这里比较容易弄错。
select * from user_test where user_name='feinik' and age=26 and city='北京';

3.1.2匹配最左前缀

匹配最左前缀是指优先匹配最左索引列,如:上面创建的索引可用于查询条件为:(user_name)、(user_name,city)、(user_name,city,age)
注:满足最左前缀查询条件的顺序与索引列的顺序无关,如:(city,user_name)、(age,city,user_name)

3.1.3匹配列前缀

指匹配列值的开头部分,如:查询用户名以feinik开头的所有用户。
select * from user_test where user_name like 'feinik%';

3.1.4匹配范围值

如:查询用户以feinik开头的所有用户,这里使用了索引的第一列。
select * from user_test where user_name like 'feinik%';

3.2索引的限制
  • where查询条件中不包含索引列中的最左索引列,则无法使用到索引查询,如:
    select * from user_test where city='北京';

    select * from user_test where age='26';

    select * from user_test where city='北京' and age=26;
  • 即使where的查询条件是最左列索引列,也无法使用索引查询用户名以feinik 结尾的用户
    select * from user_test where user_name like '%feinik';
  • 如果where查询条件中有某个列的范围查询,则其右边的所有列都无法使用索引优化查询,如:
    select * from user_test where user_name='feinik' and city like '北京%';
参考:https://www.zhihu.com/question/36996520?sort=created

你可能感兴趣的:(如何理解并正确使用MySql索引(3))