知识点:Mysql 索引原理完全手册(2)

八、 联合索引与覆盖索引

一 、联合索引

联合索引时指对表上的多个列合起来做一个索引。联合索引的创建方法与单个索引的创建方法一样,不同之处在仅在于有多个索引列,如下

mysql> create table t(
    -> a int,
    -> b int,
    -> primary key(a),
    -> key idx_a_b(a,b)
    -> ); Query OK, 0 rows affected (0.11 sec) 

那么何时需要使用联合索引呢?

从本质上来说,联合索引就是一棵B+树,不同的是联合索引的键值得数量不是1,而是>=2。

接着来讨论两个整型列组成的联合索引,假定两个键值得名称分别为a、b如图 image

可以看到这与我们之前看到的单个键的B+树并没有什么不同,键值都是排序的,通过叶子结点可以逻辑上顺序地读出所有数据,就上面的例子来说,即(1,1),(1,2),(2,1),(2,4),(3,1),(3,2),数据按(a,b)的顺序进行了存放。 因此,对于查询select * from table where a=xxx and b=xxx, 显然是可以使用(a,b) 这个联合索引的,对于单个列a的查询select * from table where a=xxx,也是可以使用(a,b)这个索引的。

但对于b列的查询select * from table where b=xxx,则不可以使用(a,b) 索引,其实你不难发现原因,叶子节点上b的值为1、2、1、4、1、2显然不是排序的,因此对于b列的查询使用不到(a,b) 索引

联合索引的第二个好处是在第一个键相同的情况下,已经对第二个键进行了排序处理

例如在很多情况下应用程序都需要查询某个用户的购物情况,并按照时间进行排序,最后取出最近三次的购买记录,这时使用联合索引可以帮我们避免多一次的排序操作,因为索引本身在叶子节点已经排序了,如下

#===========数据表==============
create table base_purchate_log(
    userid int unsigned not null,
    buy_date date
);

insert into base_purchate_log values
(1,'2009-01-01'),
(2,'2009-01-01'), (3,'2009-01-01'), (1,'2009-02-01'), (3,'2009-02-01'), (1,'2009-03-01'), (1,'2009-04-01'); alter table base_purchate_log add key(userid); alter table base_purchate_log add key(userid,buy_date); #===========数据表验证============== mysql> show create table base_purchate_log; | base_purchate_log | CREATE TABLE `base_purchate_log` ( `userid` int(10) unsigned NOT NULL, `buy_date` date DEFAULT NULL, KEY `userid` (`userid`), KEY `userid_2` (`userid`,`buy_date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | #可以看到possible_keys在这里有两个索引可以用,分别是单个索引userid与联合索引userid_2, 但是优化器最终选择了使用的key是userid因为该索引的叶子节点包含单个键值,所以理论上一个页能存放的记录应该更多 mysql> explain select * from base_purchate_log where userid=2; +----+-------------+---------+------+-----------------+--------+---------+-------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+------+-----------------+--------+---------+-------+------+-------+ | 1 | SIMPLE | base_purchate_log | ref | userid,userid_2 | userid | 4 | const | 1 | | +----+-------------+---------+------+-----------------+--------+---------+-------+------+-------+ 1 row in set (0.00 sec) #接着假定要取出userid为1的最近3次的购买记录,用的就是联合索引userid_2了,因为在这个索引中,在userid=1的情况下,buy_date都已经排序好了 mysql> explain select * from base_purchate_log where userid=1 order by buy_date desc limit 3; +----+-------------+---------+------+-----------------+----------+---------+-------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+------+-----------------+----------+---------+-------+------+--------------------------+ | 1 | SIMPLE | base_purchate_log | ref | userid,userid_2 | userid_2 | 4 | const | 4 | Using where; Using index | +----+-------------+---------+------+-----------------+----------+---------+-------+------+--------------------------+ 1 row in set (0.00 sec) #ps:如果extra的排序显示是Using filesort,则意味着在查出数据后需要二次排序 #对于联合索引(a,b),下述语句可以直接使用该索引,无需二次排序 select ... from table where a=xxx order by b; #然后对于联合索引(a,b,c)来首,下列语句同样可以直接通过索引得到结果 select ... from table where a=xxx order by b; select ... from table where a=xxx and b=xxx order by c; #但是对于联合索引(a,b,c),下列语句不能通过索引直接得到结果,还需要自己执行一次filesort操作,因为索引(a,c)并未排序 select ... from table where a=xxx order by c; 

二、 覆盖索引

InnoDB存储引擎支持覆盖索引(covering index,或称索引覆盖),即从辅助索引中就可以得到查询记录,而不需要查询聚集索引中的记录。

使用覆盖索引的一个好处是:辅助索引不包含整行记录的所有信息,故其大小要远小于聚集索引,因此可以减少大量的IO操作

注意:覆盖索引技术最早是在InnoDB Plugin中完成并实现,这意味着对于InnoDB版本小于1.0的,或者MySQL数据库版本为5.0以下的,InnoDB存储引擎不支持覆盖索引特性

对于InnoDB存储引擎的辅助索引而言,由于其包含了主键信息,因此其叶子节点存放的数据为(primary key1,priamey key2,...,key1,key2,...)。例如

select age from s1 where id=123 and name = 'duoduo'; #id字段有索引,但是name字段没有索引,该sql命中了索引,但未覆盖,需要去聚集索引中再查找详细信息。 最牛逼的情况是,索引字段覆盖了所有,那全程通过索引来加速查询以及获取结果就ok了 mysql> desc s1; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | id | int(11) | NO | | NULL | | | name | varchar(20) | YES | | NULL | | | gender | char(6) | YES | | NULL | | | email | varchar(50) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 4 rows in set (0.21 sec) mysql> explain select name from s1 where id=1000; #没有任何索引 +----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+ | 1 | SIMPLE | s1 | NULL | ALL | NULL | NULL | NULL | NULL | 2688336 | 10.00 | Using where | +----+-------------+-------+------------+------+---------------+------+---------+------+---------+----------+-------------+ 1 row in set, 1 warning (0.00 sec) mysql> create index idx_id on s1(id); #创建索引 Query OK, 0 rows affected (4.16 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> explain select name from s1 where id=1000; #命中辅助索引,但是未覆盖索引,还需要从聚集索引中查找name +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+ | 1 | SIMPLE | s1 | NULL | ref | idx_id | idx_id | 4 | const | 1 | 100.00 | NULL | +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------+ 1 row in set, 1 warning (0.08 sec) mysql> explain select id from s1 where id=1000; #在辅助索引中就找到了全部信息,Using index代表覆盖索引 +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+ | 1 | SIMPLE | s1 | NULL | ref | idx_id | idx_id | 4 | const | 1 | 100.00 | Using index | +----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+ 1 row in set, 1 warning (0.03 sec) 

覆盖索引的另外一个好处是对某些统计问题而言的。base_purchate_log,查询计划如下

mysql> explain select count(*) from base_purchate_log;
+----+-------------+---------+-------+---------------+--------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+-------+---------------+--------+---------+------+------+-------------+ | 1 | SIMPLE | base_purchate_log | index | NULL | userid | 4 | NULL | 7 | Using index | +----+-------------+---------+-------+---------------+--------+---------+------+------+-------------+ 1 row in set (0.00 sec) 

innodb存储引擎并不会选择通过查询聚集索引来进行统计。base_purchate_log,而辅助索引远小于聚集索引,选择辅助索引可以减少IO操作,故优化器的选择如上key为userid辅助索引

对于(a,b)形式的联合索引,一般是不可以选择b中所谓的查询条件。但如果是统计操作,并且是覆盖索引,则优化器还是会选择使用该索引,如下

#联合索引userid_2(userid,buy_date),一般情况,我们按照buy_date是无法使用该索引的,但特殊情况下: 查询语句是统计操作,且是覆盖索引,则按照buy_date当做查询条件时,也可以使用该联合索引 mysql> explain select count(*) from base_purchate_log where buy_date >= '2011-01-01' and buy_date < '2011-02-01'; +----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+ | 1 | SIMPLE | base_purchate_log | index | NULL | userid_2 | 8 | NULL | 7 | Using where; Using index | +----+-------------+---------+-------+---------------+----------+---------+------+------+--------------------------+ 1 row in set (0.00 sec) 

九、查询优化神器-explain

强调rows是核心指标,绝大部分rows小的语句执行一定很快(有例外,下面会讲到)。所以优化语句基本上都是在优化rows。

参考官网explain-output

执行计划:让mysql预估执行操作(一般正确)
    all < index < range < index_merge < ref_or_null < ref < eq_ref < system/const id,email 慢: select * from userinfo3 where name='alex' explain select * from userinfo3 where name='alex' type: ALL(全表扫描) select * from userinfo3 limit 1; 快: select * from userinfo3 where email='alex' type: const(走索引) 

十 、慢查询优化的基本步骤

  • 0.先运行看看是否真的很慢,注意设置SQL_NO_CACHE
  • 1.where条件单表查,锁定最小返回记录表。这句话的意思是把查询语句的where都应用到表中返回的记录数最小的表开始查起,单表每个字段分别查询,看哪个字段的区分度最高
  • 2.explain查看执行计划,是否与1预期一致(从锁定记录较少的表开始查询)
  • 3.order by limit 形式的sql语句让排序的表优先查
  • 4.了解业务方使用场景
  • 5.加索引时参照建索引的几大原则
  • 6.观察结果,不符合预期继续从0分析

十一、 慢日志管理

慢日志
            - 执行时间 > 10
            - 未命中索引
            - 日志文件路径 配置: - 内存 show variables like '%query%'; show variables like '%queries%'; set global 变量名 = 值 - 配置文件 mysqld --defaults-file='E:\wupeiqi\mysql-5.7.16-winx64\mysql-5.7.16-winx64\my-default.ini' my.conf内容: slow_query_log = ON slow_query_log_file = D:/.... 注意:修改配置文件之后,需要重启服务 

慢日志的基本操作

MySQL日志管理

  • 错误日志: 记录 MySQL 服务器启动、关闭及运行错误等信息
  • 二进制日志: 又称binlog日志,以二进制文件的方式记录数据库中除 SELECT 以外的操作
  • 查询日志: 记录查询的信息
  • 慢查询日志: 记录执行时间超过指定时间的操作
  • 中继日志: 备库将主库的二进制日志复制到自己的中继日志中,从而在本地进行重放
  • 通用日志: 审计哪个账号、在哪个时段、做了哪些事件
  • 事务日志或称redo日志: 记录Innodb事务相关的如事务执行时间、检查点等

一、bin-log
1. 启用
# vim /etc/my.cnf
[mysqld]
log-bin[=dir\[filename]]
# service mysqld restart 2. 暂停 //仅当前会话 SET SQL_LOG_BIN=0; SET SQL_LOG_BIN=1; 3. 查看 查看全部: # mysqlbinlog mysql.000002 按时间: # mysqlbinlog mysql.000002 --start-datetime="2017-12-05 10:02:56" # mysqlbinlog mysql.000002 --stop-datetime="2017-12-05 11:02:54" # mysqlbinlog mysql.000002 --start-datetime="2017-12-05 10:02:56" --stop-datetime="2017-12-05 11:02:54" 按字节数: # mysqlbinlog mysql.000002 --start-position=260 # mysqlbinlog mysql.000002 --stop-position=260 # mysqlbinlog mysql.000002 --start-position=260 --stop-position=930 4. 截断bin-log(产生新的bin-log文件) a. 重启mysql服务器 b. # mysql -uroot -p123 -e 'flush logs' 5. 删除bin-log文件 # mysql -uroot -p123 -e 'reset master' 
二、查询日志
启用通用查询日志
# vim /etc/my.cnf
[mysqld]
log[=dir\[filename]]
# service mysqld restart 
三、慢查询日志

启用慢查询日志

# vim /etc/my.cnf
[mysqld]
log-slow-queries[=dir\[filename]]
long_query_time=n
# service mysqld restart
MySQL 5.6:
slow-query-log=1
slow-query-log-file=slow.log long_query_time=3 查看慢查询日志 测试:BENCHMARK(count,expr) SELECT BENCHMARK(50000000,2*3);

猜你喜欢

转载自www.cnblogs.com/yizhiamumu/p/9205577.html