MySQL性能优化(二)索引优化

一、选择合适的列建立索引

1.在where从句,group by从句,order by从句,on从句中出现的列(select)
2.索引字段越小越好(表每页数据才会更多,IO效率会更高)
3.离散度大的列放到联合索引的前面
select * from payment where staff_id=2 and customer_id=584;
index(staff_id,customer_id)好?还是index(customer_id,staff_id)好?
由于customer_id的离散度更大(重复率小,可选择性更大),所以应该使用index(customer_id,staff_id)

二、索引维护

冗余索引是指多个索引的前缀列相同,或是在联合索引中包含了主键的索引。如下:key(name,id)就是一个冗余索引
create table test(
id int not null primary key,
name varchar(10) not null,
key(name,id)
)engine=innodb;
//可以删除冗余索引,达到优化效果。

使用pt-duplicate-key-checker工具检查重复及冗余索引
pt-duplicate-key-checker
-uroot
-p ''
-h 127.0.0.1

删除不用索引

目前mysql中还没有记录索引的使用情况,但是在PerconMySQL和MariaDB中可通过INDEX_STATISTICS表来查看哪些索引未使用,

但在mysql中目前只能通过慢查日志配合pt-index-usage工具来进行索引使用情况分析。
pt-index-usage
-uroot -p''
mysql-slow.log