mysql优化之索引

索引官方定义:索引是帮助mysql高效获取数据的数据结构。

索引的目的在于提高查询效率,可以类比字典。

可以简单理解为:排好序的快速查找数据结构

在数据之外,数据库系统还维护着满足特定查找算法的数据结构,这种数据结构以某种方式(引用)指向数据。
这样就可以在这些数据结构的基础上实现高级查找算法,这种数据结构就是索引。

例如将id加索引,在mysql数据库里开辟一块存储空间来存放索引数据,查询的时候如果根据id去查询,就要走这个索引库,在索引库找到之后,就能定位这条数据,因为索引库的每一项和数据库的物理地址是绑定的,你能找到这条索引,就能找到这条数据所对应的物理地址,就可以直接获取这条数据。

mysql优化之索引_第1张图片
一般来说索引本身也很大,不可能全部存储在内存中,因此索引往往以索引文件的形式存储在磁盘上。

索引结构

我们平常所说的索引,如果没有特别指明,都是指B树(多路搜索树,并不一定是二叉的)结构组织的索引。
其中聚集索引,次要索引,覆盖索引,复合索引,前缀索引,唯一索引默认都是使用B+树索引,统称索引。
当然,除了B+树这种类型的索引外,还有哈希索引等。

BTree索引、hash索引、full-text全文索引、R-Tree索引,我们只关注BTree索引

BTree索引检索原理

mysql优化之索引_第2张图片

索引数据为什么快?

  1. 索引数据存放是有规则的,顺序的,
  2. 查询的时候是有些算法的,例如最简单的折半
    例如索引1-26,我们找16,
    折半先找13,16比13大,就找13-26的中间值,19,
    19比16大,就找13-19的中间值,16,就找着了

如果不使用索引,就是一条条找,得找16次才能找到

索引的优缺点

  • 优点
  1. 提高数据检索的效率,降低数据库的io成本
  2. 通过索引列对数据进行排序,降低数据排序的成本,降低了cpu的消耗
  • 缺点
  1. 实际上索引也是一张表,该表保存了主键与索引字段,并指向实体表的记录,所以索引列也是要占用空间的
    索引需要占物理空间,除了数据表占数据空间之外,每一个索引还要占一定的物理空间,如果要建立聚簇索引,那么需要的空间就会更大。

  2. 虽然索引大大提高了查询速度,却会降低更新表的速度,如对表进行增删改。
    因为更新表时,mysql不仅要保存数据,还要更新添加了索引列的字段,也会调整因为更新所带来的键值变化后的索引信息

  3. 创建索引和维护索引要耗费时间,这种时间随着数据量的增加而增加。
    索引只是提高效率的一个因素,如果你的mysql有大数据量的表,就需要花时间研究建立最优秀的索引,或优化查询

    例如我们猜测客户可能会按照这样的字段去查询,就把索引建到这个字段上面,但是后面根据点击率分析和客户所筛选的条件发现,经常查询另一个字段,索引就需要优化和调整。

什么时候需要/不需要创建索引?

需要创建索引

  • 主键自动建立唯一索引
  • 频繁作为查询条件的字段应该创建索引
  • 查询中排序、统计、分组的字段
  • 查询中与其他表关联的字段,外键关系建立字段
  • 一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。

不需要创建索引

  • 表记录太少

  • 更新非常频繁的字段不适合创建索引

    除了更新数据本身外还需要更新BTree树,数据量大的话是很耗费资源的。

  • Where,分组,排序里用不到的字段不创建索引

  • 唯一性太差(字段好多都是同一个值)(在查询的时候会索引失效)的字段不适合单独(可以使用联合索引)创建索引,即使频繁作为查询条件;

索引能够极大的提高数据检索效率,也能够改善排序分组操作的性能,但是我们不能忽略的一个问题就是索引是完全独立于基础数据之外的一部分数据,更新数据会带来的IO量和调整索引所致的计算量的资源消耗。

mysql优化之索引_第3张图片

索引分类

  1. 单值索引:一个索引只包含一个列,一个表可以有多个单列索引
  2. 唯一索引:索引列的值必须唯一(身份证号),但允许有空值
  3. 复合索引:一个索引包含多列
# 创建
CREATE [UNIQUE] INDEX indexName on myTable(columnname(length));
ALTER mytable ADD [UNIQUE] INDEX [indexName] ON (columnname(length));

# 删除
DROP INDEX [indexName] ON mytable;

# 查看
SHOW INDEX FROM tableName;




# 四种方式来添加数据表的索引

# 添加一个主键,代表索引值必须是唯一的,且不能为null
ALTER TABLE tbl_name ADD PRIMARY KEY(column_list);

# 索引值必须是唯一的(除了null外,null可能会出现多次)
ALTER TABLE tbl_name ADD UNIQUE index_name(column_list);

# 添加普通索引,索引值可重复
ALTER TABLE tbl_name ADD INDEX index_name(column_list);

# 指定索引为FULLTEXT,用于全文索引
ALTER TABLE tbl_name ADD FULLTEXT index_name(column_list);

性能分析前提知识

mysql query optimizer mysq查询优化器

mysql常见瓶颈

在这里插入图片描述

explain 解释,查看sql执行计划

在这里插入图片描述
作用

  1. 表的读取顺序
  2. 数据读取操作的操作类型
  3. 哪些索引可以使用(哪些索引被实际使用)
  4. 表之间的引用
  5. 每张表有多少行被优化器查询

使用

mysql> explain select * from tbl_emp;
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------+
|  1 | SIMPLE      | tbl_emp | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    8 |   100.00 | NULL  |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)


# id(表的读取顺序)
# 	select查询的序列号,包含一组数字,表示查询中执行select子句或操作表的顺序。
#	id相同,执行顺序由上至下(就是说先加载的是tbl_dept表)
#		执行顺序和sql的编写顺序有没有关系暂时未知,测试的话是没有关系的
# 	id越大越先被执行,(如果是子查询,id的序号会递增)
#	id有相同有不同
# 		在一个sql语句中,id既有相同的,也有不同的
#		id相同,顺序执行,id越大越先被执行
#		出现这种情况实际上就是有一张虚表,就是查出一张表来给它取个别名,但是我和老师的sql一模一样就是结果不一样,有时间再看这个吧
mysql> explain select * from tbl_emp te, tbl_dept td where te.deptId=td.id;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra                                              |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
|  1 | SIMPLE      | td    | NULL       | ALL  | PRIMARY       | NULL | NULL    | NULL |    5 |   100.00 | NULL                                               |
|  1 | SIMPLE      | te    | NULL       | ALL  | fk_dept_id    | NULL | NULL    | NULL |    8 |    20.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
2 rows in set, 1 warning (0.00 sec)




mysql> explain select * from tbl_dept where id=(select deptId from tbl_emp where id=1);
+----+-------------+----------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table    | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+----------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
|  1 | PRIMARY     | tbl_dept | NULL       | const | PRIMARY       | PRIMARY | 4       | const |    1 |   100.00 | NULL  |
|  2 | SUBQUERY    | tbl_emp  | NULL       | const | PRIMARY       | PRIMARY | 4       | const |    1 |   100.00 | NULL  |
+----+-------------+----------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
2 rows in set, 1 warning (0.00 sec)




# select_type,表示select_type语句的类型(数据读取操作的操作类型)
#	simple,表示简单查询,其中不包含连接查询和子查询
#	primary,表示主查询,或者是最外面的查询语句(最后加载的那个)
# 	subquery,在select或where列表中包含了子查询
# 	derived,from列表包含的子查询,mysql会递归执行这些子查询,把结果放在临时表里。
#	union,若第二个select出现在union之后,则被标记为union;
#		若union包含在from子句的子查询中,外层select将被标记为derived
# union result 从union表获取结果的select





# type,访问类型,显示查询使用了何种类型
# 从最好到最差依次是(以下是常见的,除此之外还有很多种):
# 一般来说,得保证查询至少打到range级别,最好能达到ref
# system > const > eq_ref > ref > range > index > all
#	system 表只有一行记录(等于系统表),这是const类型的特例,平时不会出现,可以忽略不记

#	const 表示通过索引一次就找到了,const用于比较primary key或者unique索引。
#		因为只匹配一行数据,所以很快
#		如将主键置于where列表中,mysql就能将该查询转换为一个常量。

#	eq_ref 唯一性索引扫描,对于每个索引键,表中只有一条记录与之匹配。常见于主键或唯一索引扫描
#		例如两表连接,对外键设置索引,此时两表连接查询只查询到一条记录
#		例如员工表和部门表,而此时查的部门是ceo办公室,自然就只有一条记录
#简单地说是const是直接按主键或惟一键读取,eq_ref用于联表查询的状况,按联表的主键或惟一键联合查询。

#	ref 非唯一性索引扫描,返回匹配某个单独值的所有行。

#	range 只检索给定范围的行,使用一个索引来选择行
#		例如在where语句中出现between、<、>、in等的查询
#		这种范围扫描索引比全表扫描要好,因为它只需要开始于索引的某一点,而结束于另一点,不用扫描全部索引。

#	index 与all区别为index类型只遍历索引树。这通常比all快,因为索引文件通常比数据文件小。

#	all 全表扫描






# possible_keys
#	显示可能应用在这张表中的索引,一个或多个。
#	查询涉及到字段上若存在索引,则该索引将被列出,但不一定被查询实际使用



# key
#	实际使用的索引。如果为null,则没有使用索引
#	查询中若使用了覆盖索引,则该索引仅出现在key列表中
#		覆盖索引:sql语句中查询的字段和复合索引的字段、顺序都一致


# key_len
#	表示索引中使用的字节数,可通过该列计算查询中使用的索引的长度。在不损失精确性的情况下,长度越短越好
#		精度的意思是,where后跟一个条件,索引长度肯定更小,但是精度也更小
#		如果再跟一个条件,索引长度大了,但是精度肯定高了
#	key_len显示的值为索引字段的最大可能长度,并非实际使用长度,即key_len是根据表定义计算而得,不是通过表内检索出的



# ref
#	显示索引的哪一列被使用了,如果可能的话,是一个常数。哪些列或常量被用于查找索引列上的值
#		这句话的意思是,如果那一列where后面的条件值是个常量的话就显示 const,否则就是列名



# rows
#	根据表统计信息及索引选用情况,大致估算出找到所需的记录所需要读取的行数



# filtered
#	存储引擎返回的数据在server层过滤后,剩下多少满足查询的记录数量的比例
#	只做参考,不需要刻意关注

extra 包含不适合在其他列中显示但十分重要的额外信息

# using filesort(不好,尽量消除)
#	说明mysql会对数据使用一个外部的索引排序,而不是按照表内的索引顺序读取
#	mysql中无法利用索引完成的排序操作称为 文件排序
#		大概意思就是我们自己建立的索引因为一些原因没有或部分使用到,mysql内部自己又建立了一个索引

mysql优化之索引_第4张图片
以上实例,索引的顺序如果和查询排序的字段一致的话,就不会出现 using filesort,效率就更高,反之则效率更低

# Using temporary(不好,尽量消除)
#	使用临时表保存中间结果,mysql在对查询结果排序时使用临时表。
#	常见于 order by 和 group by
# 	会加大空间的占用,影响效率

mysql优化之索引_第5张图片

# using index
#	表示相应的select操作中使用了覆盖索引,避免访问了表的数据行,效率不错!
#	如果同时出现using where,表明索引被用来执行索引键值的查找
#	如果没有同时出现using where,表明索引用来读取数据而非执行查找动作


# using where
#	使用了where过滤


# using join buffer
#	使用了连接缓存
#	join使用过多,可以把配置文件的缓冲区调大
# 


# impossible where
#	where子句的值总是false,不能用来获取任何元组
#	例如 where name='zs' and name = 'ls'
#		一个人是不会有两个名字的

using filesort,using temporary, using index是重点,其他了解即可

demo

mysql优化之索引_第6张图片
在这里插入图片描述

单表优化案例

/*
UNSIGNED
	unsigned(无符号)是一种数据类型的修饰符。它可以用于整型数据类型,例如INT、BIGINT等。
		在无符号的二进制表示中,数据类型将仅仅包含非负整数。

使用unsigned的主要好处是它可以在不改变数据类型的前提下,增加数据类型所能存储的最大值。
		例如,INTUNSIGNED的最大值为4294967295,而INT的最大值仅为2147483647。
		这可以极大地提高存储空间的利用率,并且可以避免使用较大的数据类型来存储小的非负整数。

*/

show tables;
CREATE TABLE if	NOT EXISTS article(
	id INT(10) UNSIGNED NOT NULL PRIMARY KEY auto_increment,
	author_id int(10) UNSIGNED NOT NULL,
	category_id int(10) UNSIGNED NOT NULL,
	views int(10) UNSIGNED NOT NULL,
	comments int(10) UNSIGNED NOT NULL,
	title VARBINARY(255) NOT NULL,
	content text NOT NULL
	
)



INSERT INTO article(`author_id`,`category_id`,`views`,`comments`,`title`,`content`) VALUES (1,1,1,1,'1','1'),
(2,2,2,2,'2','2'),
(3,3,3,3,'3','3')




# 查询category_id为1且comments大于1的情况下,views最多的article_id
mysql> explain select id,author_id from article where category_id = 1 and comments>1 order by views desc limit 1;
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-----------------------------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra                       |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-----------------------------+
|  1 | SIMPLE      | article | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    4 |    25.00 | Using where; Using filesort |
+----+-------------+---------+------------+------+---------------+------+---------+------+------+----------+-----------------------------+
1 row in set, 1 warning (0.00 sec)


# 很显然,type all和Using filesort 都是最坏的情况,必须优化




# 一眼看到这个题是应该创建category_id,comments,views的符合索引
#	索引确实被用到了,但是文件排序依然存在
#	原因是因为 > 会导致索引失效,使索引断了

# 那我们就跳过它,只为其他两个字段建立复合索引
mysql> create index category_views on article (category_id,views);

mysql> explain select id,author_id from article where category_id = 1 and comments=1 order by views desc limit 1;
+----+-------------+---------+------------+------+----------------+----------------+---------+-------+------+----------+-------------+
| id | select_type | table   | partitions | type | possible_keys  | key            | key_len | ref   | rows | filtered | Extra       |
+----+-------------+---------+------------+------+----------------+----------------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | article | NULL       | ref  | category_views | category_views | 4       | const |    2 |    25.00 | Using where |
+----+-------------+---------+------------+------+----------------+----------------+---------+-------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

这个说的是建立三个字段的索引的情况
mysql优化之索引_第7张图片

两表优化案例

mysql> create table if not exists class(
    ->     -> id int(10) unsigned not null auto_increment,
    ->     -> card int(10) unsigned not null,
    ->     -> primary key(id)
    ->     -> )
mysql> create  table if not exists book(
    -> bookid int(10) unsigned not null auto_increment,
    -> card int(10) unsigned not null,
    -> primary key(bookid)
    -> );
Query OK, 0 rows affected (0.03 sec)


# 以下两条sql各执行8次
mysql> insert into class(card) values(floor(1+(rand()*20)));
Query OK, 1 row affected (0.00 sec)

mysql> insert into book(card) values(floor(1+(rand()*20)));
Query OK, 1 row affected (0.00 sec)





mysql> select * from class left join book on class.card=book.card;
+----+------+--------+------+
| id | card | bookid | card |
+----+------+--------+------+
|  3 |    2 |      1 |    2 |
|  4 |    2 |      1 |    2 |
|  3 |    2 |      5 |    2 |
|  4 |    2 |      5 |    2 |
|  1 |   18 |      6 |   18 |
|  2 |    3 |      7 |    3 |
|  5 |    3 |      7 |    3 |
|  6 |    7 |   NULL | NULL |
|  7 |    7 |   NULL | NULL |
|  8 |   13 |   NULL | NULL |
+----+------+--------+------+
10 rows in set (0.00 sec)

mysql> explain select * from class left join book on class.card=book.card;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra                                              |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
|  1 | SIMPLE      | class | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    8 |   100.00 | NULL                                               |
|  1 | SIMPLE      | book  | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    9 |   100.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
2 rows in set, 1 warning (0.00 sec)


mysql> create index class_card on class(card);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> explain select * from class left join book on class.card=book.card;
+----+-------------+-------+------------+-------+---------------+------------+---------+------+------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type  | possible_keys | key        | key_len | ref  | rows | filtered | Extra                                              |
+----+-------------+-------+------------+-------+---------------+------------+---------+------+------+----------+----------------------------------------------------+
|  1 | SIMPLE      | class | NULL       | index | NULL          | class_card | 4       | NULL |    8 |   100.00 | Using index                                        |
|  1 | SIMPLE      | book  | NULL       | ALL   | NULL          | NULL       | NULL    | NULL |    9 |   100.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------------+-------+---------------+------------+---------+------+------+----------+----------------------------------------------------+
2 rows in set, 1 warning (0.00 sec)


mysql> drop index class_card on class;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> create index book_card on book(card);
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> explain select * from class left join book on class.card=book.card;
+----+-------------+-------+------------+------+---------------+-----------+---------+-----------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key       | key_len | ref             | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+-----------+---------+-----------------+------+----------+-------------+
|  1 | SIMPLE      | class | NULL       | ALL  | NULL          | NULL      | NULL    | NULL            |    8 |   100.00 | NULL        |
|  1 | SIMPLE      | book  | NULL       | ref  | book_card     | book_card | 4       | test.class.card |    1 |   100.00 | Using index |
+----+-------------+-------+------------+------+---------------+-----------+---------+-----------------+------+----------+-------------+
2 rows in set, 1 warning (0.00 sec)



/*
	由上得出,左连接的时候把索引建在右表更好一些
		type是ref,rows也更小
	
	这是由左连接特性决定的。
		left join条件用于确定如何从右表搜索行,左边一定都有,
		所以右边是我们的关键点,一定要建立索引。

	
*/

三表优化案例

mysql> create table if not exists phone( phoneid int(10) unsigned not null auto_increment, card int(10) unsigned not null, primary key(phoneid)) engine=innodb;
Query OK, 0 rows affected (0.02 sec)

# 执行8次
mysql> insert into phone(card) values(floor(1+(rand()*20)));
Query OK, 1 row affected (0.02 sec)



mysql> explain select * from class left join book on class.card=book.card left join phone on book.card=phone.card;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra                                              |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
|  1 | SIMPLE      | class | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    8 |   100.00 | NULL                                               |
|  1 | SIMPLE      | book  | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    9 |   100.00 | Using where; Using join buffer (Block Nested Loop) |
|  1 | SIMPLE      | phone | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    8 |   100.00 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------------------------------------------+
3 rows in set, 1 warning (0.00 sec)




mysql> create index book_card on book(card);
Query OK, 0 rows affected (1.58 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> create index phone_card on phone(card);
Query OK, 0 rows affected (0.22 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> explain select * from class left join book on class.card=book.card left join phone on book.card=phone.card;
+----+-------------+-------+------------+------+---------------+------------+---------+-----------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key        | key_len | ref             | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------------+---------+-----------------+------+----------+-------------+
|  1 | SIMPLE      | class | NULL       | ALL  | NULL          | NULL       | NULL    | NULL            |    8 |   100.00 | NULL        |
|  1 | SIMPLE      | book  | NULL       | ref  | book_card     | book_card  | 4       | test.class.card |    1 |   100.00 | Using index |
|  1 | SIMPLE      | phone | NULL       | ref  | phone_card    | phone_card | 4       | test.book.card  |    1 |   100.00 | Using index |
+----+-------------+-------+------------+------+---------------+------------+---------+-----------------+------+----------+-------------+
3 rows in set, 1 warning (0.00 sec)

结论

  1. 尽可能减少join语句中的NestedLoop的循环总次数,永远用小结果集驱动大结果集

    例如书的种类和书的数量。

  2. 优先优化NestedLoop的内层循环

  3. 保证join语句中被驱动表上join条件字段已经被索引

  4. 当无法保证被驱动表的join条件字段被索引且内存资源充足的前提下,不要太吝惜joinBuffer的设置

索引失效(应该避免)

对查询进行优化,要尽量避免全表扫描

CREATE TABLE staffs(
id INT PRIMARY KEY auto_increment,
NAME VARCHAR(24) NOT NULL DEFAULT "" COMMENT "姓名",
age INT NOT NULL DEFAULT 0 COMMENT "年龄",
pos VARCHAR(20) NOT NULL DEFAULT "" COMMENT "职位",
add_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "入职时间"
) CHARSET utf8 COMMENT "员工记录表";

INSERT INTO staffs(name,age,pos,add_time) VALUES('z3',22,'manager',now());
INSERT INTO staffs(name,age,pos,add_time) VALUES('july',23,'dev',now());
INSERT INTO staffs(name,age,pos,add_time) VALUES('2000',23,'dev',now());

CREATE INDEX staffs ON staffs(name,age,pos);



mysql> show index from staffs;
+--------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table  | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| staffs |          0 | PRIMARY  |            1 | id          | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |
| staffs |          1 | staffs   |            1 | NAME        | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |
| staffs |          1 | staffs   |            2 | age         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |
| staffs |          1 | staffs   |            3 | pos         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |
+--------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
4 rows in set (0.00 sec)
# 全值匹配
#	严格按照索引字段的建立来查询

mysql> explain select * from staffs where name = "z3" and age = 22 and pos = "manager";
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref               | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------+
|  1 | SIMPLE      | staffs | NULL       | ref  | staffs        | staffs | 140     | const,const,const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)







# mysql索引(最佳)最左匹配
#	如果索引了多列,要遵守最左匹配原则,
#	指的是查询从索引的最左列开始并且不跳过中间索引中的列

mysql> explain select * from staffs where name = "z3";
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref   | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | staffs | NULL       | ref  | staffs        | staffs | 74      | const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)



mysql> explain select * from staffs where age = "22" and pos = "manager";
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | staffs | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    3 |    33.33 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)



# 跳过复合索引中间的一个字段之后,虽然也用到了索引,但索引只走了name一个字段
mysql> explain select * from staffs where name = "z3" and pos = "manager";
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | staffs | NULL       | ref  | staffs        | staffs | 74      | const |    1 |    33.33 | Using index condition |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-----------------------+
1 row in set, 1 warning (0.01 sec)








# 不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描
#	操作 'july' 是可以的
mysql> explain select * from staffs where left(name,4) = 'july';
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | staffs | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    3 |   100.00 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)






# 存储引擎不能使用索引中 范围条件 右边的列

# 因为type是range,证明pos字段并没有走索引
# 还想证明的话,也可以把name单拿出来,和把三个字段的索引都用上,然后观察key_len
mysql> explain select * from staffs where name='z3' and age > 1 and pos = 'manager';
+----+-------------+--------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys | key    | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | staffs | NULL       | range | staffs        | staffs | 78      | NULL |    1 |    33.33 | Using index condition |
+----+-------------+--------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)










# 尽量使用覆盖索引,减少select *
# 这儿是出现了Using index,效率更好
mysql> explain select * from staffs where name='z3' and age = 22 and pos = 'manager';
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref               | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------+
|  1 | SIMPLE      | staffs | NULL       | ref  | staffs        | staffs | 140     | const,const,const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select name,age,pos from staffs where name='z3' and age = 22 and pos = 'manager';
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref               | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------------+
|  1 | SIMPLE      | staffs | NULL       | ref  | staffs        | staffs | 140     | const,const,const |    1 |   100.00 | Using index |
+----+-------------+--------+------------+------+---------------+--------+---------+-------------------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)








# 在使用!=或者<>无法使用索引会导致全表扫描

select name from userinfo where id <> 0
# 因此对于上面的查询,正确写法可以改为
select name from userinfo where id < 0 union all
select name from userinfo where id > 0






# is null 和 is not null 也无法使用索引 
# type 为 null是极端情况
#	可以设置default值,避免null值
# 注意:当数据库中数据的索引列的null值达到较高的比例的时候,mysql的查询优化器会选择使用索引,此时type的值是range
mysql> explain select * from staffs where name is null;
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra            |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+------------------+
|  1 | SIMPLE      | NULL  | NULL       | NULL | NULL          | NULL | NULL    | NULL | NULL |     NULL | Impossible WHERE |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+------------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from staffs where name is not null;
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | staffs | NULL       | ALL  | staffs        | NULL | NULL    | NULL |    3 |    66.67 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)









# like以通配符开头 例如%abc ,索引失效导致全表扫描
#	如果在实际业务中必须把%放在前面,我们可以使用覆盖索引
#		使用覆盖索引查询时,只查询覆盖索引中的一个字段或全部,都会用到索引
#		但是如果查询覆盖索引之外的字段,甚至是 * ,则索引依然失效
mysql> explain select * from staffs where name like '%july%';
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | staffs | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    3 |    33.33 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from staffs where name like '%july';
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | staffs | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    3 |    33.33 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from staffs where name like 'july%';
+----+-------------+--------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys | key    | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | staffs | NULL       | range | staffs        | staffs | 74      | NULL |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)









# 少用or,会引起索引失效
# 少用 in 和 not in,因为in 实际上等同于 or
#	or暂时没查到最合适的说法,大部分说法是需要涉及到or的字段全部都得建立索引,而且是单独的索引
#	然而我测试过后,依然是失效的,网上查了半天也没有详尽的答案
select id from t where num in(1,2,3)    
# 对于连续的数值,能用 between 就不要用 in 了
select id from t where num between 1 and 3

 


# 很多时候用 exists 代替 in 是一个好的选择
select num from a where num in(select num from b)    # 用下面的语句替换    
select num from a where exists(select 1 from b where num=a.num)


# 唯一性太差,会引起索引失效。(例如一个字段有好多内容是相同的)
# 类型转换导致索引失效

索引面试题分析

CREATE TABLE test03(
id int PRIMARY KEY NOT NULL auto_increment,
c1 char(10),
c2 char(10),
c3 char(10),
c4 char(10),
c5 char(10)
);


INSERT INTO test03(c1,c2,c3,c4,c5) VALUES('a1','a2','a3','a4','a5');
INSERT INTO test03(c1,c2,c3,c4,c5) VALUES('b1','b2','b3','b4','b5');
INSERT INTO test03(c1,c2,c3,c4,c5) VALUES('c1','c2','c3','c4','c5');
INSERT INTO test03(c1,c2,c3,c4,c5) VALUES('d1','d2','d3','d4','d5');
INSERT INTO test03(c1,c2,c3,c4,c5) VALUES('e1','e2','e3','e4','e5');

SELECT * from test03;

CREATE INDEX idx_test03_c1234 ON test03(c1,c2,c3,c4);
# 根据 mysql索引(最佳)最左匹配
#	如果索引了多列,要遵守最左匹配原则,
#	指的是查询从索引的最左列开始并且不跳过中间索引中的列

# 以下sql应该是部分走索引或者不走索引的,但实际情况是走索引了
#	是因为mysql优化器会将我们输入的sql进行自动的调整优化以达到最优的效果
mysql> explain select * from test03 where c1='a1' and c2='a2' and c4='a4' and c3='a3';
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref                     | rows | filtered | Extra |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------------+------+----------+-------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 124     | const,const,const,const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------------+------+----------+-------+
1 row in set, 1 warning (0.01 sec)

mysql> explain select * from test03 where c4='a4' and c3='a3' and c2='a2' and c1='a1';
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref                     | rows | filtered | Extra |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------------+------+----------+-------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 124     | const,const,const,const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)





# 还是因为mysql优化器的缘故,mysql优化器将sql进行调整,就是用到索引中的四个字段了
mysql> select * from test03 where c1='a1' and c2='a2' and c4>'a4' and c3='a3';
Empty set (0.00 sec)

mysql> explain select * from test03 where c1='a1' and c2='a2' and c4>'a4' and c3='a3';
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys    | key              | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | test03 | NULL       | range | idx_test03_c1234 | idx_test03_c1234 | 124     | NULL |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)








# c3也走索引了,因为是排序,没有统计到下面的信息中
mysql> explain select * from test03 where c1='a1' and c2='a2' and c4='a4' order by c3;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref         | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+-----------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 62      | const,const |    1 |    20.00 | Using index condition |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)






mysql> explain select * from test03 where c1='a1' and c2='a2' order by c3;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref         | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+-----------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 62      | const,const |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)




# 出现了file sort
mysql> explain select * from test03 where c1='a1' and c2='a2' order by c4;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+---------------------------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref         | rows | filtered | Extra                                 |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+---------------------------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 62      | const,const |    1 |   100.00 | Using index condition; Using filesort |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+---------------------------------------+
1 row in set, 1 warning (0.00 sec)






mysql> explain select * from test03 where c1='a1' and c5='a5' order by c2,c3;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------+------+----------+------------------------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref   | rows | filtered | Extra                              |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------+------+----------+------------------------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 31      | const |    1 |    20.00 | Using index condition; Using where |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------+------+----------+------------------------------------+
1 row in set, 1 warning (0.00 sec)




mysql> explain select * from test03 where c1='a1' and c5='a5' order by c3,c2;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------+------+----------+----------------------------------------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref   | rows | filtered | Extra                                              |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------+------+----------+----------------------------------------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 31      | const |    1 |    20.00 | Using index condition; Using where; Using filesort |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------+------+----------+----------------------------------------------------+
1 row in set, 1 warning (0.00 sec)




# 上面在排序的时候颠倒了索引中的字段,产生了file sort
# 	而这儿却没有产生
# 通常情况下排序的时候颠倒索引的字段是会产生file sort
# 	有一个特例,就是排序的字段已经是常量了,那其实就没有排序的必要了
#	例如这个例子,查出来的c2已经全部是a2了,排序这个字段已经没有了意义
mysql> explain select * from test03 where c1='a1' and c2='a2' and  c5='a5' order by c3,c2;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+------------------------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref         | rows | filtered | Extra                              |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+------------------------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 62      | const,const |    1 |    20.00 | Using index condition; Using where |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+------------------------------------+
1 row in set, 1 warning (0.00 sec)


mysql> explain select * from test03 where c1='a1' and c2='a2' and  c5='a5' order by c2,c3;
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+------------------------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref         | rows | filtered | Extra                              |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+------------------------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 62      | const,const |    1 |    20.00 | Using index condition; Using where |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------+------+----------+------------------------------------+
1 row in set, 1 warning (0.00 sec)





# like % 在后面,前面的值相当于常量,其本身和后面的字段都可以用到索引
mysql> explain select * from test03 where c1='a1' and c2='a2' and c3>'a3' and c4='a3';
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys    | key              | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | test03 | NULL       | range | idx_test03_c1234 | idx_test03_c1234 | 93      | NULL |    1 |    20.00 | Using index condition |
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from test03 where c1='a1' and c2='a2' and c4 like 'a4%' and c3='a3';
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys    | key              | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | test03 | NULL       | range | idx_test03_c1234 | idx_test03_c1234 | 124     | NULL |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+-------+------------------+------------------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from test03 where c1='a1' and c2='a2' and c4 like '%a4' and c3='a3';
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys    | key              | key_len | ref               | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------+------+----------+-----------------------+
|  1 | SIMPLE      | test03 | NULL       | ref  | idx_test03_c1234 | idx_test03_c1234 | 93      | const,const,const |    1 |    20.00 | Using index condition |
+----+-------------+--------+------------+------+------------------+------------------+---------+-------------------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)

优化总结口诀

mysql优化之索引_第8张图片

order by 优化

mysql支持两种方式的排序,filesort和index,index效率高。

  1. order by子句,尽量使用index方式排序,避免使用filesort排序
  2. 尽可能在索引列上完成排序操作,遵照索引最左匹配原则
  3. 如果不在索引列上排序,filesort有两种算法
    mysql就要启动双路排序和单路排序

order by 满足两种情况会使用index方式排序:

  • order by语句使用索引最左列(与mysql索引(最佳)最左匹配一致)
  • 使用where子句与order by子句条件列组合满足索引最左列
CREATE TABLE tblA(
age int,
birth TIMESTAMP NOT null
);

INSERT INTO tblA(age,birth) values(22,now());
INSERT INTO tblA(age,birth) values(23,now());
INSERT INTO tblA(age,birth) values(24,now());

CREATE INDEX idx_A_ageBirth ON tblA(age,birth);
# order by 优化,我们只关心会不会产生filesort


# 下面的排序没有出现filesort是因为我们使用了覆盖索引,并且排序时与索引的顺序一致
mysql> explain select * from tblA where age>20 order by age;
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+--------------------------+
| id | select_type | table | partitions | type  | possible_keys  | key            | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | tblA  | NULL       | index | idx_A_ageBirth | idx_A_ageBirth | 9       | NULL |    3 |   100.00 | Using where; Using index |
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from tblA where age>20 order by age,birth;
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+--------------------------+
| id | select_type | table | partitions | type  | possible_keys  | key            | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | tblA  | NULL       | index | idx_A_ageBirth | idx_A_ageBirth | 9       | NULL |    3 |   100.00 | Using where; Using index |
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)



# 使用where子句与order by子句条件列组合满足索引最左列
mysql> explain select * from tblA where age=20 order by birth;
+----+-------------+-------+------------+------+----------------+----------------+---------+-------+------+----------+--------------------------+
| id | select_type | table | partitions | type | possible_keys  | key            | key_len | ref   | rows | filtered | Extra                    |
+----+-------------+-------+------------+------+----------------+----------------+---------+-------+------+----------+--------------------------+
|  1 | SIMPLE      | tblA  | NULL       | ref  | idx_A_ageBirth | idx_A_ageBirth | 5       | const |    1 |   100.00 | Using where; Using index |
+----+-------------+-------+------------+------+----------------+----------------+---------+-------+------+----------+--------------------------+
1 row in set, 1 warning (0.01 sec)


# order by birth,age  也同样会产生filesort
mysql> explain select * from tblA where age>20 order by birth;
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+------------------------------------------+
| id | select_type | table | partitions | type  | possible_keys  | key            | key_len | ref  | rows | filtered | Extra                                    |
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+------------------------------------------+
|  1 | SIMPLE      | tblA  | NULL       | index | idx_A_ageBirth | idx_A_ageBirth | 9       | NULL |    3 |   100.00 | Using where; Using index; Using filesort |
+----+-------------+-------+------------+-------+----------------+----------------+---------+------+------+----------+------------------------------------------+
1 row in set, 1 warning (0.00 sec)




mysql> explain select * from tblA order by age asc,birth desc;
+----+-------------+-------+------------+-------+---------------+----------------+---------+------+------+----------+-----------------------------+
| id | select_type | table | partitions | type  | possible_keys | key            | key_len | ref  | rows | filtered | Extra                       |
+----+-------------+-------+------------+-------+---------------+----------------+---------+------+------+----------+-----------------------------+
|  1 | SIMPLE      | tblA  | NULL       | index | NULL          | idx_A_ageBirth | 9       | NULL |    3 |   100.00 | Using index; Using filesort |
+----+-------------+-------+------------+-------+---------------+----------------+---------+------+------+----------+-----------------------------+
1 row in set, 1 warning (0.00 sec)

filesort的单路排序和双路排序

  • 双路排序
    mysql4.1之前是使用双路排序,字面意思就是扫描两次磁盘,最终得到数据
    读取行指针和order by列,对他们进行排序,然后扫描已经排序好的列表,按照列表中的值重新从列表中读取对应的数据输出。

    从磁盘取排序字段,在buffer进行排序再从磁盘读取其他字段。

读取一批数据,磁盘进行两次扫描,众所周知,io是很耗时的,所以在mysql4.1之后,出现了第二种改进的算法,就是单路排序

  • 单路排序
    在这里插入图片描述

单路排序的问题

由于单路是后出的,总体而言好过双路

但是用单路有问题

在这里插入图片描述
解决
sql服务器调优

mysql优化之索引_第9张图片

mysql优化之索引_第10张图片

总结

mysql优化之索引_第11张图片

group by优化

在这里插入图片描述
其他的均和order by一致

正如 丘吉尔所说,世界上没有永远的朋友,也没有永远的敌人,只有永恒的利益。

鬼吹灯
天下霸唱

部分知识引用自:
https://www.bilibili.com/video/BV1KW411u7vy/?p=5&spm_id_from=pageDriver&vd_source=64c73c596c59837e620fed47fa27ada7

你可能感兴趣的:(mysql,数据库)