MySQL 如何重命名mysql中的外键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6188011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I rename a foreign key in mysql?
提问by Simon
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?
删除和重新添加约束将意味着另外两个长查询。有没有办法在单个查询中重命名约束?
回答by bradoaks
From the documentation:
从文档:
Multiple ADD, ALTER, DROP, and CHANGEclauses are permitted in a single ALTER TABLEstatement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.
单个ALTER TABLE语句中允许使用多个ADD、ALTER、DROP和CHANGE子句,并用逗号分隔。这是标准 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`);
回答by VAShhh
I'm sorry, but constraints can only be dropped and re-attacched in mySQL
抱歉,约束只能在 mySQL 中删除并重新附加
回答by VGE
The feature does not seems to be available in mysql ALTER TABLE syntax.
该功能在 mysql ALTER TABLE 语法中似乎不可用。
However it is supported for Oracle.
但是,它受 Oracle 支持。
回答by RxBx
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
请参考我在MySQL 术语“约束”与“外键”区别中的回答?了解为什么约束名称与您想要的不同。但是,MySQL 没有重命名约束功能,因此需要使用所需的 name DROP 和 ADD FK。 https://dev.mysql.com/doc/refman/5.5/en/alter-table.html