使用mysql中的concat创建复合索引

时间:2014-04-28 10:47:09

标签: mysql grouping concat

使用以下命令,我可以获得create index命令,

SELECT CONCAT ('
create index ',index_name,' on ',table_schema,'.',table_name,' (',COLUMN_NAME,');'  
) FROM 
inf_schema.STATS WHERE 
table_schema='employee' AND 
table_name='FILESPROC' AND 
index_name NOT LIKE 'PRIMARY' ;

我得到以下输出:

create index FILENAMEPROCID on employee.FILESPROCESSED (PROCID);
create index FILENAMEPROCID on employee.FILESPROCESSED (FILENAME);
create index NENDDATEDataName on employee.FILESPROCESSED (DSN);
create index NENDDATEDataName on employee.FILESPROCESSED (ENDDATE);
create index NENDDATEDataName on employee.FILESPROCESSED (DataName);
create index DSN on employee.FILESPROCESSED (DSN);
create index ENDDATE on employee.FILESPROCESSED (ENDDATE);

但是,我需要以下列方式输出:

create index FILENAMEPROCID on employee.FILESPROCESSED (PROCID, FILENAME);
create index NENDDATEDataName on employee.FILESPROCESSED (DSN, ENDDATE, DataName);
create index DSN on employee.FILESPROCESSED (DSN);
create index ENDDATE on employee.FILESPROCESSED (ENDDATE);

这样我就可以创建复合索引了。我怎么做到这一点?

1 个答案:

答案 0 :(得分:1)

对具有相同GROUP_CONCAT的所选COLUMN_NAME使用INDEX_NAME

SELECT 
        CONCAT (
          'create index ', index_name, ' on ', table_schema, '.', table_name, 
          ' ( ', GROUP_CONCAT( COLUMN_NAME SEPARATOR ', ' ), ' );'  
        ) indexes_scripts
  FROM 
        inf_schema.STATS 
 WHERE 
        table_schema='employee' 
   AND  table_name='FILESPROC'
   AND  index_name NOT LIKE 'PRIMARY' 
 GROUP BY index_name