简体   繁体   中英

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:

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?

The SHOW INDEX doesn't have enough information. 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. 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.

I have expanded on Bill's good answer above. Output options are expanded to include ADD PRIMARY KEY, ADD UNIQUE INDEX, or 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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