目录
[1. 生成删除索引 SQL 语句](#1. 生成删除索引 SQL 语句)
[2. 生成创建索引的 SQL 语句](#2. 生成创建索引的 SQL 语句)
[3. 生成分析表的 SQL 语句](#3. 生成分析表的 SQL 语句)
1. 生成删除索引 SQL 语句
mysql -uwxy -p12345 -S /data/18253/mysqldata/mysql.sock -e "
select concat('alter table \`',table_schema,'\`.\`',table_name,'\` ',drop_index,';')
from (
select table_schema, table_name, group_concat(if(index_name='PRIMARY','drop primary key',concat('drop index \`',index_name,'\`'))) drop_index
from (
select distinct table_schema, table_name, index_name
from information_schema.statistics
where table_schema in ('test')
and (table_schema, table_name, index_name) not in (
select t1.table_schema, t1.table_name, t1.index_name
from information_schema.statistics t1, information_schema.columns t2
where t1.table_schema in ('test')
and t1.table_schema = t2.table_schema and t1.table_name = t2.table_name and t1.column_name = t2.column_name
and t2.extra='auto_increment')) t
group by table_schema, table_name) t;" -N > drop_index.sql
2. 生成创建索引的 SQL 语句
mysql -uwxy -p12345 -S /data/18253/mysqldata/mysql.sock -e "
select concat('alter table \`',table_schema,'\`.\`',table_name,'\` ',create_index,';')
from (
select table_schema, table_name, group_concat(if(index_name='PRIMARY',concat('add primary key (',index_columns,')'),concat('add index \`',index_name,'\` (',index_columns,')'))) create_index
from (
select table_schema, table_name, index_name, group_concat(concat('\`',column_name,'\`') order by seq_in_index) index_columns
from information_schema.statistics
where table_schema in ('test')
and (table_schema, table_name, index_name) not in (
select t1.table_schema, t1.table_name, t1.index_name
from information_schema.statistics t1, information_schema.columns t2
where t1.table_schema in ('test')
and t1.table_schema = t2.table_schema and t1.table_name = t2.table_name and t1.column_name = t2.column_name
and t2.extra='auto_increment')
group by table_schema, table_name, index_name) t
group by table_schema, table_name) t;" -N > create_index.sql
3. 生成分析表的 SQL 语句
mysql -uwxy -p12345 -S /data/18253/mysqldata/mysql.sock -e "
select concat('analyze table \`',table_schema,'\`.\`',table_name,'\`;')
from information_schema.tables
where table_schema in ('test');" -N > analyze_table.sql