遇到的问题:分库分表情况下可能好几百张表,可以使用存储过程来新建索引。实现方式如下
1 /*新建存储过程:给库.表的字段添加索引*/ 2 delimiter $$ 3 /*创建带参存储过程 dbName库名称;tablePrefixName表名称前缀;minTableNumber表最小序号;maxTableNumber表最大序号;indexName索引名称;indexValue索引列*/ 4 create PROCEDURE add_index_while_procure(IN dbPrefixName VARCHAR(50),IN tablePrefixName VARCHAR(50),IN minTableNumber INT,IN maxTableNumber INT,IN indexName varchar(50),IN indexValue varchar(200)) 5 BEGIN 6 declare table_name_number int; 7 8 set table_name_number=minTableNumber; 9 while(table_name_number<=maxTableNumber) DO 10 /*添加索引语句*/ 11 set @STMT :=CONCAT("alter table ",dbPrefixName,".",tablePrefixName,table_name_number," ADD index " ,indexName," ",indexValue,";"); 12 /*输出执行语句*/ 13 select @STMT; 14 prepare STMT FROM @STMT; 15 EXECUTE STMT; 16 17 set table_name_number=table_name_number+1; 18 end while; 19 END 20 $$ 21 delimiter;
1 /*调用存储过程 所有子表及主表 2 ALTER TABLE manager.tableName ADD INDEX idx_station_time (STATION_CODE, TIME) USING BTREE ; 3 */ 4 call add_index_while_procure("manager","tableName_",1906,1912,"idx_code_time","(CODE, TIME)");
/*查看存储过程*/ show procedure status; show create procedure add_index_while_procure;
/*存在则删除存储过程*/ drop procedure if EXISTS add_index_while_procure;
1 /*新建存储过程:删除给库.表的字段索引*/ 2 delimiter $$ 3 /*创建带参存储过程 dbName库名称;tablePrefixName表名称前缀;minTableNumber表最小序号;maxTableNumber表最大序号;indexName索引名称;indexValue索引列*/ 4 create PROCEDURE drop_index_while_procure(IN dbPrefixName VARCHAR(50),IN tablePrefixName VARCHAR(50),IN minTableNumber INT,IN maxTableNumber INT,IN indexName varchar(50)) 5 BEGIN 6 declare table_name_number int; 7 8 set table_name_number=minTableNumber; 9 while(table_name_number<=maxTableNumber) DO 10 /*添加索引语句*/ 11 set @STMT :=CONCAT("alter table ",dbPrefixName,".",tablePrefixName,table_name_number," DROP index " ,indexName,";"); 12 /*输出执行语句*/ 13 select @STMT; 14 prepare STMT FROM @STMT; 15 EXECUTE STMT; 16 17 set table_name_number=table_name_number+1; 18 end while; 19 END 20 $$ 21 delimiter;
1 /*调用存储过程 所有子表及主表 2 ALTER TABLE manager.tableName DROP INDEX idx_station_time; 3 */ 4 call drop_index_while_procure("manager","tableName_",1906,1912,"idx_station_time");
参考:
https://blog.csdn.net/qq_23132561/article/details/100888454