Question

Using the following command I am being able to get the create index command,

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' ;

I get the following output:

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);

However, I need the output in the following manner:

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);

so that I am able to create composite indexes. How am I to achieve this?

Was it helpful?

Solution

Use GROUP_CONCAT on selected COLUMN_NAME that have same 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top