【mysql】根据数据库现有的索引生成删除和新增索引的语句

#生成创建索引语句
SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,' ADD ',CASE WHEN NON_UNIQUE=0 THEN 'UNIQUE' ELSE '' END,' INDEX ',INDEX_NAME,'(',GROUP_CONCAT(COLUMN_NAME),');') 
FROM information_schema.`statistics`
WHERE TABLE_SCHEMA='表名' AND INDEX_NAME!='PRIMARY'
GROUP BY TABLE_SCHEMA,TABLE_NAME,INDEX_NAME
ORDER BY SEQ_IN_INDEX;

#生成删除索引语句
SELECT CONCAT('ALTER TABLE ',TABLE_SCHEMA,'.',TABLE_NAME,' DROP INDEX ',INDEX_NAME,';') 
FROM information_schema.`statistics` 
WHERE TABLE_SCHEMA='表名' AND INDEX_NAME!='PRIMARY'
GROUP BY TABLE_SCHEMA,TABLE_NAME,INDEX_NAME;

 

posted @ 2023-05-23 16:35  huangzebin  阅读(23)  评论(0编辑  收藏  举报