1, 整合 DDL 语句
在将索引添加到 MySQL 表的过程中, 一个很重要的问题就是 DDL 语句时阻塞性, 把多条 alter 语句整合成一条 SQL 语句时一种简单的优化改进.
例如:
- alter table test add index(username);
- alter table test drop index name,add index name(last_name,first_name);
- alter table test add column laset_visit date null;
改成:
- alter table test
- add index(username),
- drop index name,
- add index name(last_name,first_name),
add column laset_visit date null;
该优化能够大幅度提升管理任务的性能.
2, 去除重复索引
重复的索引有两个主要的影响: 第一, 所有 DML 语句都会运行的更慢, 因为需要更多工作来保持数据和索引的一致性; 第二, 数据库的磁盘占用量会更大, 这将导致备份和恢复的时间增加.
例如:
- create table test
- (id int unsinged not null,
- first_name varchar(30) not null,
- last_name varchar(30) not null,
- joined date not null,
- primary key(id),
- index (id)
- );
这个 DDL 中 id 列上的索引是重复的索引, 需要将其移除.
当一个给定索引的最左边部分被包含在其他索引中时也会产生重复索引.
- create table test
- (id int unsinged not null,
- first_name varchar(30) not null,
- last_name varchar(30) not null,
- joined date not null,
- primary key(id),
- index name1 (last_name),
- index name2 (last_name,first_name)
- );
name1 这个索引是多余的, 因为此索引所在的列已经被包含在索引 name2 的最左边部分里面了.
3, 删除不用的索引
除了重复索引没有被使用到之外, 还有其他索引可能也没有被用到, 这些索引和重复索引一样会影响性能.
4, 监控无效的索引
当定义多列索引时, 一定要注意确定所指定的每一列是否真的有效, 可以通过分析指定表上的所有 SQL 语句的 key_len 列来找到那些可能包含没有使用到的列的索引.
来源: http://www.linuxidc.com/Linux/2018-04/151842.htm