mysql:遍历表并更改表添加索引

2022-01-24 00:00:00 iteration mysql alter-table

我有 ~1000 个以相同前缀开头的表:table_prefix_{SOME_ID}(我可以从另一个表中获取 id)

I have ~1000 tables that start with the same prefix : table_prefix_{SOME_ID} (i can take the ids from another table)

在 mysql 中循环 所有 表并执行以下操作的快速方法是什么:

what is the fast way to loop over all the tables in mysql and do :

   ALTER TABLE `table_prefix_{some_id}` ADD INDEX `fields` (`field`)

推荐答案

忘记循环.只需这样做:

Forget looping. Just do this:

select concat( 'alter table ', a.table_name, ' add index `fields` (`field`);' )
from information_schema.tables a 
where a.table_name like 'table_prefix_%';

然后获取结果集并将其作为 SQL 脚本运行.

Then take the result set and run it as a SQL script.

顺便说一句,你的意思可能是 create index index_name on table_name(column_name);

BTW, you probably mean create index index_name on table_name( column_name);

相关文章