clean up table in MySQL which uses auto increment

Viewed 820

My table looks like this:

table_id | letters
-------- | -------
     4   |    a
    10   |    b
    24   |    c
    78   |    d
   110   |    e
   234   |    f

table_id uses the option AUTO_INCREMENT. (those values came because of a weird bug in my program ... don't ask :-) )

I want to clean it up with the following result:

table_id | letters
-------- | -------
    1    |    a
    2    |    b
    3    |    c
    4    |    d
    5    |    e
    6    |    f

Is that possible?

And is there a way to clean this automatically up via cronjob or something?


Solution:

The 1st solution of Gordons answer did work properly. But i needed to add some code because the auto_increment didn't want to reset automatically. The final solution is:

SET @rn := 0;

UPDATE t 
SET 
    table_id = (@rn:=@rn + 1)
ORDER BY table_id;

SELECT 
    COUNT(*)
INTO @AutoInc FROM
    t;

SET @s:=CONCAT('ALTER TABLE t AUTO_INCREMENT=', @AutoInc + 1);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

(to reset the counter i used this solution)

3 Answers
Related