美文网首页
02.你猜MySQL哪种索引快?

02.你猜MySQL哪种索引快?

作者: 乐活骑士 | 来源:发表于2020-06-26 11:18 被阅读0次

猜想

        MySQL哪种索引快?聚簇索引 or 非聚簇索引

试验用表

# 这是一个普通的表小t
CREATE TABLE `t` (
  `id` int(10) NOT NULL COMMENT '大家好,我是主键',
  `a` int(11) DEFAULT NULL COMMENT '大家好,我是字段a,我是一个普通索引',
  `b` int(11) DEFAULT NULL COMMENT '我是一个字段,我没有索引',
  PRIMARY KEY (`id`),
  KEY `a` (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='大家好,我是表`t`'

起因

        在某个风和日丽的下午,大家伙正在沟通业务的时候,引发了一场“辩论”:主键查询会比普通索引查询快吗?

  • 正方:以primary key为条件查询快
  • 反方:效率一样

浅谈索引

        MySQL的索引主要两类,聚簇索引(也叫主键索引、聚集索引)和非聚簇索引(也叫非聚集索引、二级索引、普通索引)。目前MySQL innoDB引擎的索引,主要使用B+树结构,B+树的深度低,叶子节点多,可以有效减少磁盘IO,提升性能。

MySQL的索引结构

        MySQL中每张表的数据,也以B+树的结构保存。同为B+树结构,它与索引的区别是:叶子节点保存的是主键 + 数据,而普通索引保存的是索引值 + 主键,如下图所示。

主键索引数据结构(下图)

image.png

普通索引(下图)

image.png

查询与回表

        那么MySQL查询是如何工作的呢?我想聪明的你已经知道了答案。
        如果我们通过主键查询(比如下面SQL语句),那么innoDB引擎会在保存聚簇索引的这颗B+树中,寻找id = 4的节点,然后通过指针直接获取行数据。

# 根据聚集索引查询数据,一枪头
select * from t where id = 4;

        如果我们通过普通查询(比如下面SQL语句),那么innoDB引擎会在保存普通索引的这颗B+树中,寻找a = 'd'的节点,然后在叶子节点中获取到主键值,再通过主键去查询真实数据,这个过程就叫做回表,显然它比通过聚簇索引去查询,多一步

# 根据普通索引查询数据,回表一次
select * from t where a = 'd';

        这里有个小知识点,如果我们只需要查询a字段的值,那么普通索引的叶子节点已经包含了结果,就不需要回表了。学名叫做——索引覆盖

实操

        鉴于前排的理论知识,我们来进行一番实操,步骤如下:

  1. 环境:本机docker mysql:5.6.47
  2. 版本:MySQL 5.6.47
  3. init table
  4. init data
  5. have a try
# step 1 init table
CREATE TABLE `t` (
  `id` int(10) NOT NULL COMMENT '你好,我是主键',
  `a` int(11) DEFAULT NULL COMMENT '大家好,我是字段a,我是一个普通索引',
  `b` int(11) DEFAULT NULL COMMENT '我是一个字段,我没有索引',
  PRIMARY KEY (`id`),
  KEY `a` (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='大家好,我是表`t`'
# step 2 init data
# 插入100w数据
DROP PROCEDURE if exists idata;
delimiter ;;
create procedure idata()
begin
  declare i int;
  set i=1;
  while(i<=100000)do
    insert into t values(i, i, i);
    set i=i+1;
  end while;
end;;
delimiter ;
call idata();

# step 3 test
语句1:select * from t where id < 100000; -- 0.10s
语句2:select * from t where  a < 100000; -- 0.30s

        结果体现出,主键索引更快,而且执行速度差距有点大,我们来看看执行计划。

mysql> explain select * from t where id < 100000;
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------------+
| id | select_type | table | type  | possible_keys | key     | key_len | ref  | rows   | Extra       |
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------------+
| 1  | SIMPLE      | t     | range | PRIMARY       | PRIMARY | 4       | NULL | 200664 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+------+--------+-------------+
1 rows in set (0.02 sec)

mysql> explain select * from t where  a < 100000;
+----+-------------+-------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------------+
| 1  | SIMPLE      | t     | ALL  | a             | NULL | NULL    | NULL | 998222 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------------+
1 rows in set (0.02 sec)


        通过执行计划发现,字段a竟然没有命中索引,执行了全表扫描!
        ==出现这种情况,简单来说,是由于优化器判定扫描行数过多,而且通过索引a查询我们想要的数据,每次都需要通过再次查询主键索引,代价过高,所以放弃使用索引a。==
        那么我们可以强制语句走索引a,再试试查询效果。显然这次使用到了索引。

mysql> explain select * from t force index(a) where  a < 100000;
+----+-------------+-------+-------+---------------+------+---------+------+--------+-----------------------+
| id | select_type | table | type  | possible_keys | key  | key_len | ref  | rows   | Extra                 |
+----+-------------+-------+-------+---------------+------+---------+------+--------+-----------------------+
| 1  | SIMPLE      | t     | range | a             | a    | 5       | NULL | 205002 | Using index condition |
+----+-------------+-------+-------+---------------+------+---------+------+--------+-----------------------+
1 rows in set (0.09 sec)

        再来执行一遍试试看,果然,执行效率上来说:主键索引 > 普通索引 > 全表扫描,附上分析细节,重点关注Sending data

select * from t where id < 100000;  -- 0.10s
select * from t where  a < 100000;  -- 0.25s
select * from t force index(a) where  a < 100000;   -- 0.13s



mysql> show profiles;
+----------+------------+--------------------------------------------------+
| Query_ID | Duration   | Query                                            |
+----------+------------+--------------------------------------------------+
| 1        | 0.00049450 | set profiling = 1                                |
| 2        | 0.09794425 | select * from t where id < 100000                |
| 3        | 0.25010650 | select * from t where a < 100000                 |
| 4        | 0.12352975 | select * from t force index(a) where  a < 100000 |
+----------+------------+--------------------------------------------------+
4 rows in set (0.02 sec)


mysql> show profile for query 2;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000086 |
| checking permissions | 0.000013 |
| Opening tables       | 0.000077 |
| init                 | 0.000042 |
| System lock          | 0.000042 |
| optimizing           | 0.000028 |
| statistics           | 0.000109 |
| preparing            | 0.000035 |
| executing            | 0.000017 |
| Sending data         | 0.097321 |
| end                  | 0.000079 |
| query end            | 0.000015 |
| closing tables       | 0.000018 |
| freeing items        | 0.000042 |
| cleaning up          | 0.000021 |
+----------------------+----------+
15 rows in set (0.05 sec)

mysql> show profile for query 3;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000121 |
| checking permissions | 0.000019 |
| Opening tables       | 0.000037 |
| init                 | 0.000030 |
| System lock          | 0.000027 |
| optimizing           | 0.000019 |
| statistics           | 0.000056 |
| preparing            | 0.000022 |
| executing            | 0.000014 |
| Sending data         | 0.249550 |
| end                  | 0.000027 |
| query end            | 0.000015 |
| closing tables       | 0.000023 |
| freeing items        | 0.000115 |
| cleaning up          | 0.000034 |
+----------------------+----------+
15 rows in set (0.05 sec)

mysql> show profile for query 4;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000072 |
| checking permissions | 0.000017 |
| Opening tables       | 0.000037 |
| init                 | 0.000029 |
| System lock          | 0.000028 |
| optimizing           | 0.000019 |
| statistics           | 0.000075 |
| preparing            | 0.000023 |
| executing            | 0.000014 |
| Sending data         | 0.123024 |
| end                  | 0.000027 |
| query end            | 0.000012 |
| closing tables       | 0.000017 |
| freeing items        | 0.000052 |
| cleaning up          | 0.000085 |
+----------------------+----------+
15 rows in set (0.01 sec)

        经过以上分析,开始时的“辩论”,我想你心中已有答案。

 
 
 

翻车

        其实到这里,故事应该已经结束了,本着熟能生巧的原则,我去测试服务器上再实操了一遍,却出现了意想不到的结果。

环境

1. 环境:阿里云RDS
2. 版本:MySQL 5.6.16-log

现象

语句1:select * from t where id < 100000; -- 0.50s
语句2:select * from t where  a < 100000; -- 0.51s
语句3:select * from t force index (a) where  a < 100000; -- 0.42s
  1. 全表扫描和主键查询时间差不多??
  2. 普通索引查询比主键查询还要快??
image.png

        同样的MySQL,同样的配方,结果让人大跌眼镜!

为什么呢?

        经过一顿分析,并没有发现云rds与本机MySQL有什么区别。目前我正在寻找这个问题的答案,并且正在与阿里云官方积极沟通中,如果你知道其中原委,还请留言告知,不吝赐教!

相关文章

  • 02.你猜MySQL哪种索引快?

    猜想 MySQL哪种索引快?聚簇索引 or 非聚簇索引? 试验用表 起因 在某个风和日丽的下午,大家伙正在沟通业务...

  • MySQL查漏补缺

    MySQL查漏补缺 目录 唯一索引比普通索引快吗, 为什么MySQL由哪些部分组成, 分别用来做什么MySQL查询...

  • MySQL查询性能优化七种武器之链路追踪

    MySQL优化器可以生成Explain执行计划,我们可以通过执行计划查看是否使用了索引,使用了哪种索引? 但是到底...

  • MySQL索引及查询优化书目录

    MySQL索引的原理之索引目的 MySQL索引的原理之索引原理 MySQL索引的原理之索引的类型 MySQL索引的...

  • mysql的索引呢?你又知道多少?

    mysql的索引呢?你又知道多少? 在Java面试中必问mysql,问mysql的时候索引也是必问,可见索引有多么...

  • 高性能的索引策略

    MySQL查询基础-查询执行过程 MySQL聚簇索引 MySQL覆盖索引 MySQL索引扫描排序 MySQL冗余和...

  • MySQL索引的使用

    MySQL索引 MySQL索引可以快速提高MySQL的检索速度。索引分单列索引和组合索引单列索引:即一个索引只包含...

  • 数据库能跑得快少不了这7个MySQL优化建议!

    前言 什么是Mysql?你真的知道吗? MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数...

  • mysql索引

    索引简介 索引(index)是帮助mysql高效获取数据的数据结构,即索引是数据结构。 可以理解为:==排好序的快...

  • Mysql索引与锁

    本文以Mysql5.7为例测试。 1:mysql索引方法 Mysql的索引方法分为btree索引和hash索引。 ...

网友评论

      本文标题:02.你猜MySQL哪种索引快?

      本文链接:https://www.haomeiwen.com/subject/srgyfktx.html