生成 MySQL 删除索引、创建索引、分析表的 SQL 语句

2023-10-14 09:57:14 浏览数 (2)


1. 生成删除索引的 SQL 语句

代码语言:javascript复制
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 语句

代码语言:javascript复制
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,'`', if(sub_part is null,'',concat('(',sub_part,')'))) 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 语句

代码语言:javascript复制
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

0 人点赞