Query to Re-index Primary Key of MySQL Database

风格不统一 提交于 2019-11-30 11:44:05

问题


I've got a table in MySQL that has a Primary Key Column.

Lets say:

ID | Value
1  | One
2  | Two
6  | Three
8  | Four
9  | Five

How do I get it to be:

ID | Value
1  | One
2  | Two
3  | Three
4  | Four
5  | Five

There are no other tables. Just the one. I just want the ID to be in a proper series.

Any suggestion?? A Query perhaps.. :)


回答1:


There is even a simple way to accomplish the result by writing this query

SET @newid=0;
UPDATE tablename SET primary_key_id=(@newid:=@newid+1) ORDER BY primary_key_id;

This query will reindex the primary key starts from 1




回答2:


Seems to me you have two options.

1) create a new table and copy the existing data over.

2) add another autoincrement field to the existing table, then delete the original column.

ALTER TABLE tableName ADD NewIdn INT NOT NULL AUTO_INCREMENT KEY



回答3:


I did this in phpmyadmin by unchecking the A_I box (Auto Increment setting), clicking save, and then checking it again, and clicking save again.



来源:https://stackoverflow.com/questions/10242311/query-to-re-index-primary-key-of-mysql-database

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