MySql 索引优化

2017-03-13  本文已影响37人  zshanjun

如何选择合适的列建立索引

1、在where从句,group by从句,order by从句,on 从句中出现额列
2、索引字段越小越好
3、离散度大的列放到联合索引的前面(可以用count(distinct field)来比较)

索引的维护及优化---重复及冗余索引

重复索引是指相同的列以相同顺序建立的同类型的索引,如下表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

冗余索引是指多个索引的前缀列相同,或是在联合索引中包含了主键的索引(对于innodb中每个索引中都会包含主键)

下面的例子中key(name, id)就是一个冗余索引

create table test(
 id int not null primary key,
 name varchar(10) not null,
 title varchar(50) not null,
 key(name,id)
) engine=innodb

冗余索引维护工具pt-duplicate-key-checker

使用方法:pt-duplicate-key-checker -uroot -ppassword -h127.0.0.1

示例(为测试提前在yarns表建立了index(code, id)冗余索引):

# ########################################################################
# sfabric.yarns
# ########################################################################

# Key idx_code_id_index ends with a prefix of the clustered index
# Key definitions:
#   KEY `idx_code_id_index` (`code`,`id`),
#   PRIMARY KEY (`id`),
# Column types:
#         `code` varchar(255) collate utf8_unicode_ci not null comment '??'
#         `id` int(10) unsigned not null auto_increment
# To shorten this duplicate clustered index, execute:
ALTER TABLE `sfabric`.`yarns` DROP INDEX `idx_code_id_index`, ADD INDEX `idx_code_id_index` (`code`);

# ########################################################################
# Summary of indexes
# ########################################################################

# Size Duplicate Indexes   7710
# Total Duplicate Indexes  1
# Total Indexes            394


删除不用的索引

目前MySQL中还没有记录索引的使用情况,但是在PerconaMySQL和MariaDB中通过INDEX_STATISTICS表来查看哪些索引未被使用,但在MySQL中目前只能通过慢查询日志配合pt-index-usage工具来进行索引使用情况的分析

用法:

pt-index-usage -uroot -ppassword mysql-slow.log


参考网站:

上一篇下一篇

猜你喜欢

热点阅读