如何在MySQL中将SHOW INDEX转换为ALTER TABLE来添加索引



我在一个表上做了SHOW INDEX,这是我得到的输出:

Table: logfile
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 759103
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:

给定这些信息,我如何构建ALTER语句以向表添加索引?

SHOW INDEX没有足够的信息。你可以试试:

select concat('ALTER TABLE `', table_schema, '`.`', table_name, '` ADD ', 
if(non_unique, '', 'UNIQUE '), 'INDEX `', index_name, '` (', 
group_concat('`', column_name, '`' order by seq_in_index), ');') as _ddl
from information_schema.statistics 
where (table_schema, table_name) = (?, ?) 
group by table_schema, table_name, index_name, non_unique;

您需要在我留下占位符?,?的地方填写模式和表名。

这只是让你开始。我知道它没有考虑到一些选项,包括前缀索引、表达式索引或注释。我将把它留给读者作为练习。

还会为每个索引生成一个单独的alter table语句。如果希望通过一个alter表来添加所有索引,可以使用子查询为每个索引生成列列表,然后在外部查询中使用group_concat()来组合它们。

我已经扩展了上面Bill的好答案。将输出选项扩展为包括ADD主键、ADD唯一索引或ADD INDEX

select concat('ALTER TABLE ', table_schema, '.', table_name, ' ADD ', 
if(index_name = 'PRIMARY', 'PRIMARY KEY ', if(non_unique, 'INDEX ', 'UNIQUE INDEX ')), 
if (index_name = 'PRIMARY','', index_name), ' (', group_concat('', column_name, '' order by seq_in_index), ');') 
as 'alter table statement'
from information_schema.statistics 
where table_schema = '<add your table schema here>' 
group by table_schema, table_name, index_name, non_unique
order by table_schema, table_name, non_unique asc

最新更新