如何重命名mysql中的外键?

发布于 2024-11-11 12:53:30 字数 367 浏览 3 评论 0原文

我们刚刚在一个大表上完成了一个长时间运行的迁移,并最终在我们的conversation_tags表上得到了以下约束:

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

不幸的是,某处有一个错误,因为我们想要的是:

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

删除并重新添加约束意味着另外两个长查询。有没有办法在单个查询中重命名约束?

We've just completed a long-running migration on a large table, and ended up with the following constraint on our conversation_tags table:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

像你 2024-11-18 12:53:30

来自文档

一个文件中允许有多个 ADDALTERDROPCHANGE 子句
单个 ALTER TABLE 语句,以逗号分隔。 这是一个 MySQL
对标准 SQL 的扩展,每个子句仅允许一个
ALTER TABLE 语句。

这样,您可以将删除和重新创建合并到一个查询中,这应该比删除约束并在两个查询中创建它更快:

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

From the documentation:

Multiple ADD, ALTER, DROP, and CHANGE clauses are permitted in a
single ALTER TABLE statement, separated by commas. This is a MySQL
extension to standard SQL, which permits only one of each clause per
ALTER TABLE statement.

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`);
烏雲後面有陽光 2024-11-18 12:53:30

抱歉,约束只能在 mySQL 中删除并重新附加

I'm sorry, but constraints can only be dropped and re-attacched in mySQL

陌伤ぢ 2024-11-18 12:53:30

该功能似乎在 mysql ALTER TABLE 语法中不可用。

但是 Oracle 支持它。

The feature does not seems to be available in mysql ALTER TABLE syntax.

However it is supported for Oracle.

云胡 2024-11-18 12:53:30

请参考我的答案MySQL术语“约束”与“外部”键”差异? 了解为什么约束名称与您想要的不同。
然而,MySQL 没有重命名约束功能,因此需要使用所需的名称 DROP 和 ADD FK 。
https://dev.mysql.com/doc/refman/ 5.5/en/alter-table.html

Please refer to my answer in MySQL terminology "constraints" vs "foreign keys" difference? 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 .
https://dev.mysql.com/doc/refman/5.5/en/alter-table.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文