一.如何选择合适的列建立索引
1.在where从句,group by从句,order by从句,on从句中出现的列.
2.在索引字段越小越好.
3.离散度大的列放到联合索引的前面
判断离散度
查看列唯一值的数量,数量越大,离散度越大.
select count(distinct customer_id),count(distinct staff_id) from payment;
二.索引优化SQL的方法
1.重复索引
是指相同的列以相同的顺序建立的同类型索引,如下表中的primary key和ID列上的索引就是重复索引.
create table test(
id int not null primary key,
name varchar(10) not null,
title varchar(50) not null,
unique(id)
)engine=innodb;
2.查找重复索引
可以使用工具pt-duplicate-key-checker
use information_schema
select a.table_schema as '数据表'
,a.table_name as '表名'
,a.index_name as '索引1'
,b.index_name as '索引2'
,a.column_name as '重复列名'
from statistics a join statistics b on
a.table_schema=b.table_schema
and a.table_name=b.table_name
and a.seq_in_index=b.seq_in_index
and a.column_name=b.column_name
where a.seq_in_index=1 and a.index_name<>b.index_name;
三.删除不使用的索引
在perconMySQL和MariaDB中可以通过index_staatistics表来查看哪些索引未使用
在MySQL中目前只能通过慢查询日志配合pt-index-usage工具来进行索引使用情况的分析.