简体   繁体   中英

Check if a column is indexed - MySql

I need to write a script to check if a column is indexed in the table it belongs to, if not then add an index for it. MySQL doesn't seem to have ADD INDEX IF NOT EXISTS .

What's the best way to do this in MySQL?

See http://dev.mysql.com/doc/refman/5.1/en/create-index.html

There is a stored procedure that does this (remember, not my code, just the first hit on google with mysql add index if not exists as search string).

DELIMITER $$
DROP PROCEDURE IF EXISTS `create_index_if_not_exists`$$

CREATE DEFINER=`user`@`%` PROCEDURE `create_index_if_not_exists`(table_name_vc varchar(50), index_name_vc varchar(50), field_list_vc varchar(200))
SQL SECURITY INVOKER
BEGIN

set @Index_cnt = (
select  count(1) cnt
FROM    INFORMATION_SCHEMA.STATISTICS
WHERE   table_name = table_name_vc
and index_name = index_name_vc
);

IF ifnull(@Index_cnt,0) = 0 THEN set @index_sql = concat('Alter table ',table_name_vc,' ADD INDEX ',index_name_vc,'(',field_list_vc,');');

PREPARE stmt FROM @index_sql;
EXECUTE stmt;

DEALLOCATE PREPARE stmt;

END IF;

END$$
DELIMITER ;

There is an alternative version right underneath it in the same page.

也许这可以帮助你:

SHOW INDEX FROM my_table WHERE Key_name = 'index_to_check';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM