MySQL数据库优化返回列表
上传时间:2015-02-02 内容关键字:MySQL数据库优化
二、索引优化SQL的方法:
重复及冗余索引的认识:
索引不仅会增加插入和更新的负担,也会增加查询的负担。因为索引越多,分析的过程就会越慢。重复索引是指相同的列以相同的顺序建立的同类型索引,如下表中的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;
重复和冗余索引的查找:
第一步:建立上面的test表作为测试:
第二步:使用我们已经编写好的检测程序:
第三步:找到重复和冗余的索引所在的库和表
第四部:进入该库,查询该表的结果确定重复和冗余的索引,然后删除。
核心检测代码:
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;
建立好test数据库后,开始测试:
mysql> use information_schema;
Database changed
mysql> 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;
+----------+------+---------+---------+----------+
| 数据库名 | 表名 | 索引1 | 索引2 | 重复列名 |
+----------+------+---------+---------+----------+
| hello | test | id | PRIMARY | id |
| hello | test | PRIMARY | id | id |
+----------+------+---------+---------+----------+
mysql> use hello
Database changed
mysql> show create table test;
+-------+------------------------------------------------------------------------+
| Table | Create Table |
+-------+------------------------------------------------------------------------+
| test | CREATE TABLE `test` (
`id` int(11) NOT NULL,
`name` varchar(10) NOT NULL,
`title` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`) 重复索引,建议删除
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-------+-------------------------------------------------------------------------+