简体   繁体   English

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

[英]How to convert SHOW INDEX into ALTER TABLE to add Index in MySQL

I did SHOW INDEX on a table and this is the output I got:我在桌子上SHOW INDEX ,这是我得到的 output:

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:

Given this information, how do I structure the ALTER statement to add an Index to the table?鉴于此信息,我如何构造ALTER语句以将索引添加到表中?

The SHOW INDEX doesn't have enough information. SHOW INDEX 没有足够的信息。 You can try this:你可以试试这个:

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;

You would need to fill in the schema and table name where I left placeholders?, ?.您需要在我留下占位符的地方填写模式和表名?,?。

This is just to get you started.这只是为了让你开始。 I know it doesn't account for a few options including prefix indexes, expression indexes, or comments.我知道它没有考虑一些选项,包括前缀索引、表达式索引或注释。 I'll leave that as an exercise for the reader.我将把它留给读者作为练习。

Also it would generate a separate alter table statement for each index.它还会为每个索引生成一个单独的 alter table 语句。 If you want to do one alter table to add all indexes, use a subquery to generate the column list for each index, and then group_concat() to combine them in the outer query.如果你想做一个alter table来添加所有索引,使用一个子查询为每个索引生成列列表,然后group_concat()在外部查询中组合它们。

I have expanded on Bill's good answer above.我在上面扩展了比尔的好答案。 Output options are expanded to include ADD PRIMARY KEY, ADD UNIQUE INDEX, or ADD INDEX Output 选项扩展为包括 ADD PRIMARY KEY、ADD UNIQUE INDEX 或 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM