How to update id set from 1?

為{幸葍}努か 提交于 2019-12-30 05:08:12

问题


I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

id  name
3   ABC
5   XYZ
9   PQR

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

id  name
1   ABC
2   XYZ
3   PQR

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks


回答1:


Is there any query to update my existing id and make my id start from 1 and next id 2 and so on

What you can do is transfer the content of your table to another table. Reset the auto increment counter, insert your data back into the original table but let MySQL assign the primary key.

Assuming your table name is mytable You do it like this:

CREATE TABLE mytable_tmp select * from mytable;
TRUNCATE TABLE mytable;
ALTER TABLE mytable AUTO_INCREMENT = 1;
INSERT INTO mytable(name) SELECT name FROM mytable_tmp ORDER BY id;
DROP TABLE mytable_tmp;



回答2:


In my opinion you shouldn't mess with auto_increment columns at all. Let them be as they are. Their only job is to identify a row uniquely. If you want a nice serial number use another column (make it unique if you wish)!

You will always run into trouble and there will always happen things, that mess with your nice 1, 2, 3, ... sequence. A transaction gets rolled back? Boom, your sequence is 1, 2, 3, 5, ... instead of your intended 1, 2, 3, 4, ...

This can also be a very heavy operation. An auto_increment column is always also a primary key. Every other index on this table includes the primary key. Every time you reset your auto_increments, every index on this table is rewritten.

So my advice is, don't mess with auto_increments.




回答3:


Of course there is a way:

set @counter = 0;
update table_name
set id  = (@counter := @counter + 1);

EDIT

To avoid problem with duplicate keys you can run something like this before to temporary change current ids to negative equivalents:

update table_name
set id  = 0 - id;



回答4:


This query will work for your scenario:

ALTER TABLE tablename DROP id

ALTER TABLE tablename ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id), AUTO_INCREMENT=1


来源:https://stackoverflow.com/questions/43137040/how-to-update-id-set-from-1

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