简体   繁体   English

检查列是否已编制索引 - MySql

[英]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 . MySQL似乎没有ADD INDEX IF NOT EXISTS

What's the best way to do this in MySQL? 在MySQL中执行此操作的最佳方法是什么?

See http://dev.mysql.com/doc/refman/5.1/en/create-index.html 请参阅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). 有一个存储过程可以做到这一点(记住,不是我的代码,只是谷歌的第一次点击与mysql add index if not exists作为搜索字符串)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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