MySQL 将主键列添加到无主键旧表中

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

Add a primary key column in to a no primay key old table

mysqlprimary-key

提问by jojo

If a table, data might be duplicated amount rows, and there is not primary key for every row,

如果是一个表,数据可能是重复的行数,而且每一行都没有主键,

can i add an column to be a primary key?

我可以添加一列作为主键吗?

回答by Jason McCreary

Yes. Add a new column and set it as the primary key with AUTO_INCREMENT. Doing so will create a new column and automatically add a unique id for each row.

是的。添加一个新列并将其设置为主键AUTO_INCREMENT。这样做将创建一个新列并自动为每一行添加一个唯一的 id。

ALTER TABLE old_table ADD pk_column INT AUTO_INCREMENT PRIMARY KEY;

回答by DrColossos

This is possible with ALTER TABLE(Assuming you have a column that you want to use as a PK)

这可以通过ALTER TABLE 实现(假设您有一个要用作 PK 的列)

ALTER TABLE table 
ADD PRIMARY KEY(column)

Alternativly:

或者:

ALTER TABLE table 
ADD your_pk_column INT(11) AUTO_INCREMENT PRIMARY KEY