How do I rename an Index in MySQL
我想重命名索引。我看过alter table文档,但无法弄清楚简单重命名索引的语法。通过MySQL GUI进行操作时,它将删除索引并创建一个新索引。在此可行的同时,我想避免只是为了更改索引的名称而重建整个索引。
[附加信息]
在alter table文档中指出
Alterations that modify only table
metadata and not table data can be
made immediately by altering the
table's .frm file and not touching
table contents. The following changes
are fast alterations that can be made
this way:
1 * Renaming a COLUMN OR INDEX.
但是,当我尝试通过编辑.frm文件(在测试数据库上)并重新启动服务器来重命名索引时,它现在在尝试列出列时以及在用户界面中指出"无法获取列"尝试运行查询时,它返回错误"未知表引擎"。 .frm文件包含很多二进制内容。是否有一个用于编辑二进制信息的好工具。
我在2009年回答了这个问题。当时MySQL中没有语法可以重命名索引。
从那时起,MySQL 5.7引入了
http://dev.mysql.com/doc/refman/5.7/en/alter-table.html部分说:
RENAME INDEX old_index_name TO new_index_name renames an index. This is a MySQL extension to standard SQL. The content of the table remains unchanged.old_index_name must be the name of an existing index in the table that is not dropped by the sameALTER TABLE statement.new_index_name is the new index name, which cannot duplicate the name of an index in the resulting table after changes have been applied. Neither index name can bePRIMARY .
MySQL的早期版本,例如在5.6及更早版本中,
唯一的解决方案是
MySQL中没有
关于上述更新:也许文档不够精确。无论如何,都没有用于重命名索引的SQL语法。
索引是可以从数据中重建的数据结构(实际上,建议使用
关于
对于MySQL 5.7:
1 | ALTER TABLE tbl_name RENAME INDEX old_index_name TO new_index_name |
对于MySQL旧版本:
1 | ALTER TABLE tbl_name DROP INDEX old_index_name, ADD INDEX new_index_name (...) |
请参见http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
这个问题是很久以前才提出的,最近一次是在半年前更新的。
我仍然觉得需要添加此提示:
如果索引列在其他地方用作外键,则可能会遇到与此相关的错误。这样做可能会有所帮助:
1 2 3 4 | SET FOREIGN_KEY_CHECKS = 0; ALTER TABLE tbl DROP INDEX index_name; ALTER TABLE tbl ADD INDEX new_index_name (indexed_column); SET FOREIGN_KEY_CHECKS = 1; |
希望有人觉得这有用。