mysql,更改列删除主键并自动递增

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

mysql, alter column remove primary key and auto incremement

mysqlsqlmysql-error-1075

提问by Brett

I'm changing my mysql db table from an id (auto) to a uid.

我正在将我的 mysql db 表从 id (auto) 更改为 uid。

ALTER TABLE companies DROP PRIMARY KEY;
ALTER TABLE companies ADD PRIMARY KEY (`uuid`);

This is the error I get..

这是我得到的错误..

[SQL] ALTER TABLE companies DROP PRIMARY KEY;
[Err] 1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

Which I understand, I need to change the id to a non-autoincrement because I drop it as the primary key.? What is the syntax to change a column to remove primary key and auto increment?

据我了解,我需要将 id 更改为非自动增量,因为我将其作为主键删除。?更改列以删除主键和自动增量的语法是什么?

ALTER TABLE companies change id id ?????????? int(11)

回答by Lauri Lehtinen

If you need to remove the auto-increment and the primary key from the idcolumn in a single SQL statement, this should do:

如果您需要从id单个 SQL 语句中的列中删除自动增量和主键,则应执行以下操作:

ALTER TABLE companies DROP PRIMARY KEY, CHANGE id id int(11);

In fact, you should be able to do everything in a single ALTER TABLEquery:

实际上,您应该能够在单个ALTER TABLE查询中完成所有操作:

ALTER TABLE companies
DROP PRIMARY KEY,
CHANGE id id int(11),
ADD PRIMARY KEY (uuid);

回答by Ray

When you're not changing the name of the column you can use MODIFY:

当您不更改列的名称时,您可以使用MODIFY

ALTER TABLE `companies` MODIFY `id` int(11), 
                           DROP PRIMARY KEY, 
                   ADD PRIMARY KEY (`uuid`);

By doing this all in one alter statement it's also treated as atomic, so there's no chance of inconsistency between queries (unlike running multiple statement in row).

通过在一个 alter 语句中完成所有这些操作,它也被视为原子性的,因此查询之间不会出现不一致的情况(与连续运行多个语句不同)。

回答by John

The query for remove auto increment is:

删除自动增量的查询是:

alter table companies DROP PRIMARY KEY,
change id id int(11) NOT NULL

Now you can see structure of table is without auto increment.

现在您可以看到表的结构没有自动增量。

If you want to add primary key another column, then use this query

如果要在另一列中添加主键,请使用此查询

alter table companies add PRIMARY KEY(uuid)

If you want to drop auto increment,primary key and add primary key to new column in same query, then use this query

如果要删除自动增量,主键并将主键添加到同一查询中的新列,请使用此查询

alter table comapnies DROP PRIMARY KEY,
   change id id int(11) NOT NULL,
   add PRIMARY KEY(uuid)