简体   繁体   English

如何重命名 mysql 中的外键?

[英]How do I rename a foreign key in mysql?

We've just completed a long-running migration on a large table, and ended up with the following constraint on our conversation_tags table:我们刚刚在一个大表上完成了一个长时间运行的迁移,并最终在我们的 conversation_tags 表上得到了以下约束:

CONSTRAINT `conversation_tags_ibfk_1` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`)

Unfortunately, there was a bug somewhere, because what we wanted was:不幸的是,某处有一个错误,因为我们想要的是:

CONSTRAINT `fk_conversation_tags_tags` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`)

Dropping and re-adding the constraint would mean another two long queries.删除和重新添加约束将意味着另外两个长查询。 Is there any way to rename the constraint in a single query?有没有办法在单个查询中重命名约束?

From the documentation :文档中:

Multiple ADD , ALTER , DROP , and CHANGE clauses are permitted in a single ALTER TABLE statement, separated by commas.单个ALTER TABLE语句中允许使用多个ADDALTERDROPCHANGE子句,以逗号分隔。 This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.这是标准 SQL 的 MySQL 扩展,每个 ALTER TABLE 语句只允许每个子句中的一个。

This way you can combine the drop and recreate into one query, and that should be faster than dropping the constraint and creating it in two queries:这样,您可以将删除和重新创建组合到一个查询中,这应该比删除约束并在两个查询中创建它更快:

ALTER TABLE conversation_tags
DROP FOREIGN KEY `conversation_tags_ibfk_1`,
ADD CONSTRAINT `fk_conversation_tags_tags` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`);

I'm sorry, but constraints can only be dropped and re-attacched in mySQL抱歉,只能在 mySQL 中删除和重新附加约束

The feature does not seems to be available in mysql ALTER TABLE syntax. mysql ALTER TABLE 语法中似乎没有该功能。

However it is supported for Oracle.但是它支持 Oracle。

Please refer to my answer in MySQL terminology "constraints" vs "foreign keys" difference?请参考我在MySQL 术语“约束”与“外键”区别中的回答? to understand why the constraint name was different than what you desired.了解为什么约束名称与您想要的不同。 However, MySQL doesnot have rename constraint feature and hence need to DROP and ADD FK with desired name.但是,MySQL 没有重命名约束功能,因此需要使用所需的名称 DROP 和 ADD FK。 https://dev.mysql.com/doc/refman/5.5/en/alter-table.html https://dev.mysql.com/doc/refman/5.5/en/alter-table.html

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

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