如何重命名 MySQL 中的主键列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2703126/
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 primary key column in MySQL?
提问by Vinicius Rocha
How do I rename a primary key column in MySQL?
如何重命名 MySQL 中的主键列?
回答by Igor Serebryany
it's no different than altering any other column --
这与更改任何其他列没有什么不同-
ALTER TABLE `pkey` CHANGE `keyfield` `keyfield2` INT( 11 ) NOT NULL AUTO_INCREMENT
this changes the column keyfield
in table pkey
to be called keyfield2
-- you have to supply the definition afterwards, as usual.
这会更改要调用的keyfield
表中的列- 您必须像往常一样在之后提供定义。pkey
keyfield2
回答by Dirigible
Leave off the PRIMARY KEY part of the alter statement. The primary key will be updated automatically.
去掉alter 语句的PRIMARY KEY 部分。主键会自动更新。
回答by Alex
Maybe you have a foreign key constraint in place. You can disable those by SET foreign_key_constraints=0
but you have to remember to update the database afterwards.
也许你有一个外键约束。您可以禁用这些,SET foreign_key_constraints=0
但您必须记住之后更新数据库。
回答by Samuel De Rycke
Possible a bad practice work around. But you could export your entire db to an sql text file. Find and replace the PK you want to rename, and then restore the database over sql.
可能是一种不好的做法。但是您可以将整个数据库导出到 sql 文本文件。找到并替换你要重命名的PK,然后通过sql恢复数据库。
回答by Eric Clack
If you are working with InnoDB then I think you cannot rename primary keys, at least you can't if they are referenced by foreign keys. You need to dump the database, rename the columns and referencing keys in the dump file, then reload the database.
如果您正在使用 InnoDB,那么我认为您不能重命名主键,至少如果它们被外键引用则不能。您需要转储数据库,重命名转储文件中的列和引用键,然后重新加载数据库。
回答by Remy Mellet
If others tables has foreign key on your table, you cannot directly rename the column using alter table, it will throws the following error: [HY000][1025] Error on rename of xxx to yyy (errno: 150) You must :
如果其他表在你的表上有外键,你不能直接使用alter table重命名列,它会抛出以下错误:[HY000][1025] Error on rename of xxx to yyy (errno: 150) 你必须:
- drop foreign keys from others tables pointing to the primary key you want to rename
- rename the primary key
- add the foreign column to others tables
- 从其他表中删除指向要重命名的主键的外键
- 重命名主键
- 将外部列添加到其他表
When renaming a table in Intellij, it generates you the code do drop and add the foreign key.
在 Intellij 中重命名表时,它会生成代码 do drop 并添加外键。