How do I rename a primary key column in MySQL?

2019-01-24 01:29发布

How do I rename a primary key column in MySQL?

6条回答
疯言疯语
2楼-- · 2019-01-24 01:59

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.

查看更多
看我几分像从前
3楼-- · 2019-01-24 02:00

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.

查看更多
够拽才男人
4楼-- · 2019-01-24 02:03

Leave off the PRIMARY KEY part of the alter statement. The primary key will be updated automatically.

查看更多
女痞
5楼-- · 2019-01-24 02:06

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.

查看更多
时光不老,我们不散
6楼-- · 2019-01-24 02:22

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.

查看更多
Viruses.
7楼-- · 2019-01-24 02:23

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 :

  • 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.

查看更多
登录 后发表回答