开发者

Re-Indexing MySQL INT Primary Keys & Reset AUTO_INCREMENT

So I have a MySQL database that I'm using with a PHP site. Over the course of weeks of development, I'm left with something like:

Table: users

id  | name
-----------
  12| Bob
  34| Jen
 155| John
 154| Kyle

Except this goes on for hundreds of re开发者_JAVA百科cords and the ids are in the thousands.

I'm looking for a script I can run to re-name the keys to their lowest value (preserving their respective rows), and then reset the AUTO_INCREMENT to the next id

The desired output would be:

Table: users

id  | name
-----------
   1| Bob
   2| Jen
   3| Kyle
   4| John

And ALTER TABLE users AUTO_INCREMENT = 5;

(Notice Kyle and John)

I realize I would have to fix anything referencing the users.id.

Does anyone know a way to do this in MySQL or with a PHP script?


remove index on id

do something like this:

SET @rank:=0;
update users
set id=@rank:=@rank+1
order by id;

add index on id


Why do you need to change the order of the names in the database? You can just add an ORDER BY name clause on your sql query to get the results in alphabetical order by name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜