MySQL:更改我的 PRIMARY KEY 的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6741042/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:32:52  来源:igfitidea点击:

MySQL: alter the columns of my PRIMARY KEY

mysqldatabase

提问by StackOverflowNewbie

I have a table with the following primary key:

我有一个包含以下主键的表:

PRIMARY KEY (`Id`,`InputOutputConfigurationServerAccountId`,`Identifier`)

I want to modify this so that the PK is only the Idcolumn. How do I do this?

我想修改它,以便 PK 只是Id列。我该怎么做呢?

回答by Bohemian

The problem seems to be that you have Iddefined as auto_increment. You need to first change it to just plain int, them make the changes, then turn it back to auto_increment.
Try this:

问题似乎是您已Id定义为auto_increment. 您需要首先将其更改为纯 int,他们进行更改,然后将其转回 auto_increment。
尝试这个:

ALTER TABLE SO1 MODIFY COLUMN ID INT;
ALTER TABLE SO1 DROP PRIMARY KEY;
ALTER TABLE SO1 ADD PRIMARY KEY (id);
ALTER TABLE SO1 MODIFY COLUMN ID INT AUTO_INCREMENT;

Here's a test of the above (btw, I got the error you mentioned in your comment on other answer if I didn't first modify the column):

这是对上述内容的测试(顺便说一句,如果我没有先修改该列,我会收到您在对其他答案的评论中提到的错误):

drop table if exists SO1;
create table SO1 (
  id int auto_increment,
  InputOutputConfigurationServerAccountId int,
  Identifier int,
  PRIMARY KEY (`Id`,`InputOutputConfigurationServerAccountId`,`Identifier`)
);
ALTER TABLE SO1 MODIFY COLUMN ID INT;
ALTER TABLE SO1 DROP PRIMARY KEY;
ALTER TABLE SO1 ADD PRIMARY KEY (id);
ALTER TABLE SO1 MODIFY COLUMN ID INT AUTO_INCREMENT;
show create table SO1;

All executed OK. Final Output:

全部执行正常。最终输出:

CREATE TABLE `SO1` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `InputOutputConfigurationServerAccountId` int(11) NOT NULL DEFAULT '0',
  `Identifier` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`)
)

回答by Mike

  1. Remove the old PK ALTER TABLE table_name DROP PRIMARY KEY
  2. Add the new PK ALTER TABLE table_name ADD PRIMARY KEY (Id)
  1. 删除旧的PK ALTER TABLE table_name DROP PRIMARY KEY
  2. 添加新的PK ALTER TABLE table_name ADD PRIMARY KEY (Id)