mysql, alter column remove primary key and auto incremement

时间秒杀一切 提交于 2019-12-04 10:13:44

问题


I'm changing my mysql db table from an id (auto) to a 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?

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

回答1:


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

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

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

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



回答2:


When you're not changing the name of the column you can use 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).




回答3:


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)


来源:https://stackoverflow.com/questions/3090442/mysql-alter-column-remove-primary-key-and-auto-incremement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!