Re-Indexing MySQL INT Primary Keys & Reset AUTO_INCREMENT

两盒软妹~` 提交于 2019-12-19 09:58:04

问题


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 records 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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/6629402/re-indexing-mysql-int-primary-keys-reset-auto-increment

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