본문 바로가기
MySql

MySQL Add index to table if it does not exist

by 베이스 공부 2020. 11. 19.
반응형

ALTER 구문을 사용하여 테이블에 인덱스를 추가하고 싶지만 먼저 테이블에 이미 존재하는지 확인하고 존재하지 않는 경우에만 인덱스를 추가합니다.

 ALTER TABLE tableName ADD INDEX IX_Table_XYZ (column1);

이렇게 할 수있는 방법이 있습니까?

 

해결 방법

 

다음과 같이 시도하십시오.

set @x := (select count(*) from information_schema.statistics where table_name = 'table' and index_name = 'IX_Table_XYZ' and table_schema = database());
set @sql := if( @x > 0, 'select ''Index exists.''', 'Alter Table TableName ADD Index IX_Table_XYZ (column1);');
PREPARE stmt FROM @sql;
EXECUTE stmt;

 

참조 페이지 https://stackoverflow.com/questions/30259196

 

 

반응형

댓글