如果表不存在,请向表添加索引

时间:2015-05-15 12:09:38

标签: mysql indexing alter

我想使用ALTER语法向表中添加索引,但首先要检查表中是否已存在索引,如果索引不存在则只添加索引。

 ALTER TABLE tableName ADD INDEX IX_Table_XYZ (column1);

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:9)

试试这样:

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;

答案 1 :(得分:2)

您可以使用此语法检查索引(按索引名称)是否存在

SELECT 1        
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'yourschema' AND TABLE_NAME='yourtable' AND
INDEX_NAME='yourindex';

然后你可以在像

这样的存储过程中运行它
IF (SELECT 1        
    FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = 'yourschema' AND TABLE_NAME='yourtable' AND
    INDEX_NAME='yourindex') != 1 THEN

Alter Table TableName ADD Index IX_Table_XYZ (column1);

END IF;

答案 2 :(得分:0)

根据@KayNelson的回答,对我而言,在MySQL 5.7.16中,正确的方法是在IS NULL条件下使用!=1而不是IF

因此有条件向表中添加INDEX的代码段是:

IF (SELECT 1        
    FROM `INFORMATION_SCHEMA`.`STATISTICS`
    WHERE `TABLE_SCHEMA` = 'yourschema' 
    AND `TABLE_NAME` = 'yourtable'
    AND `INDEX_NAME` = 'yourindex') IS NULL THEN

    ALTER TABLE `yourtable` ADD INDEX `yourindex` (`column1` ASC);

END IF;