679 views
Mysql

9.SQL优化之索引、排序

文章目录

索引优化

建立符合索引

语法:create index 索引名称 on 表名(字段1,字段2,字段3...);
create index idx_students_NameAgeHigh on students(name,age,high);

记忆口诀

全值匹配我最爱,最左前缀要遵守 (建立的所有索引都用上是最好的)

带头大哥不能死,中间兄弟不能断 (name字段索引不能缺,1,2,3层楼不能断层)

索引列上少计算,范围之后全失效  (max(age) age索引失效,出现>,<,!=这样的范围条件,后面的所有会失效)

like百分写最右,覆盖索引不写星 ('ying%' 避免使用select * ,最好用字段select name...)

不等空值还有or,索引失效要少用 (不等于!=,空值is null,or 语法会使索引失效,尽量不用)

varchar引号不可丢,SQL高级也不难(在定义表的字段时,如果是varchar类型,
在查询时该字段的参数必须带上引号,不然会面临辞退危险!!!!)

实例:假设index(a,b,c)

where语句 索引是否被使用到
where a = 3 Y,使用到a
where a = 3 and b = 5 Y,使用到a,b
where a = 3 and b = 5 and c = 4 Y,使用到a,b,c
where b = 3 或 where b = 3 and c = 4 或 where c = 4 N
where a = 3 and c = 5 使用到a,c没有被使用,b中间断了
where a = 3 and b > 4 and c = 5 使用到了a,b
where a = 3 and b like ‘kk%’ and c = 4 使用到了a,b,c
where a = 3 and b like ‘%kk’ and c = 4 使用到了a
where a = 3 and b like ‘%kk%’ and c = 4 使用到了a

排序优化

永远使用小表驱动大表

示例1:
for i in range(5):
    for j in range(1000):
        pass
示例2:
for i in range(1000):
    for j in range(5):
        pass

上述两个示例中,示例1就是小表驱动大表,在数据库中也类似,
在写sql的时候也要遵循这个原则        

order by优化

order by子句,尽量使用index方式排序,避免使用filesort方式排序

MySQL支持两种方式的排序,filesort和index
index效率高,MySQL扫描索引本身完成排序
filesort方式效率较低

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

1. order by 语句使用索引最左前列
2. 使用where子句与order by子句条件组合满足索引最左前列

主要意思还是口诀中的:
带头大哥不能死,中间兄弟不能断 (name字段索引不能缺,1,2,3层楼不能断层)

filesort有两种算法-双路排序和单路排序

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

2.单路排序:
从磁盘读取查询需要的所有列,按照order by列在buffer对他们进行排序,
然后扫描排序后的列表进行输出,它的效率更快一些,避免了第二次读取数据,
并且把随机IO变成了顺序IO,但是它会使用更多的空间


3.优化策略调整MySQL参数
增加sort_buffer_size参数设置
增大max_lenght_for_sort_data参数的设置

提高order by的速度

order by时select * 是一个大忌,只写需要的字段
- 当查询的字段大小总和小于max_length_for_sort_data而且排序字段不是text|blob类型时,会用改进后的算法--单路排序

两种算法的数据都有可能超出sort_buffer的容量,超出之后,会创建tmp文件进行合并排序,导致多次I/O
- 尝试提高sort_buffer_size
- 尝试提高max_length_for_sort_data

实例

索引 a_b_c(a,b,c)

order by a,b                  #使用a,b索引
order by a,b,c                #使用a,b,c索引
order by a desc,b desc,c desc #使用a,b,c索引

where a = const order by b,c  #使用a,b,c索引
where a = const and b = const order by c #使用a,b,c索引
where a = const and b > const order by b,c #使用a,b,c索引,这里虽然用了>范围,但是后面的又把b层接上了

order by a asc,b desc,c desc   #一升一降,b索引失效
where g = const order by b,c   #g不在索引中,bc索引失效
where a = const order by c     #没有b索引,出现断层,c索引失效  
where a = const order by a,d   #d不在索引中

主要还是口诀里面的内容,最佳左前缀法则
影子专属博客 赣ICP备17013143号