zfxcms ^回到顶部

您的当前位置:首页 > 最新IT资讯 > MySQL > mysql优化-索引优化

mysql优化-索引优化

所属分类: MySQL   2020-03-18 20:09:58  编辑:admin  浏览次数 534 次

1、为什么索引能够提升效率

关系型数据库存储是有序的,正常就是直接进行全表扫描,建立btree或者hash的索引以后,通过索引来查找数据能够大量提升查询效率,一条数据查询只会使用一个索引。

2、索引类型

Btree: myisam、innodb默认的索引(排好序的快速查找结构)

Hash:时间复杂度(0(1))

弱点:hash的结果是根据id随机存储、不能进行范围优化、排序、无法使用前缀索引

3、什么情况使用索引

当使用不以通配符开始的like

Select * from table1 where username like ‘pack%’;

一个索引字段的前缀使用了order by或者group by;

Select * from table2 order by field1;

对索引字段使用了>,=,<,>=,<=,IS NULL和BETWEEN

Select * from table3 where total_fee IS NULL

查找某个字段的最大值和最小值

Select  min(score),max(score) from table4 where class_id = 1;

查询的列是后面字段的部分时间

Select time1 from table5 where time2 = ‘2017-2’;

4、什么情况不使用索引

如果通过索引查询的时间大于全表扫描的时间,不使用索引

Select * from table1 where score > 59 and score < 80;

以通配符开始的like查询

Select * from table1 where username like ‘%pack%’;

搜索某列,而在另一个列的索引做order by

Select * from table2 where course = ‘php’ order by score;

Heap:在heap表中使用order by

5、误区

不是在where条件常用的列都加上索引

Where course = ‘php’ and number > 50;

在多列建立索引后,查询哪个列,都将发挥作用?

满足左前缀要求。

Index(field1,field2,field3)

Where  field1 = 1                            生效

Where  field1 = 1 and field2 =2       生效

Where  field1 = 1 and field2 =2 and field3 = 3;  生效

Where   field2 =2     Where   field3 =3  不生效

Where  field1 = 1  and field3 = 3;  field1生效,field3不生效

Where  field1 = 1 and field2 >2 and field3 = 3;  field1和field2生效,field3不生效

Where  field1 = 1 and field2  like ‘pack%’  and field3 = 3;

field1和field2生效,field3不生效

最左前缀:

字段是有序的;

image.png

查询离散度,离散度越大,筛选掉的数据越多,剩下的数据越少,速度越快选择一个能够淘汰最多纪录的索引;

image.png

image.png


image.png

image.png

搜索的索引列:

唯一索引:大量的无意义的记录

短索引:部分长度索引(磁盘I/O)

不能过度索引:

比较、模糊查询

image.png

随笔文章检索

随笔文章目录