How to fill in the “holes” in auto-increment fields?

后端 未结 7 907
时光说笑
时光说笑 2020-11-27 06:12

I\'ve read some posts about this but none cover this issue.

I guess its not possible, but I\'ll ask anyway.

I have a table with more than 50.000 registers. I

7条回答
  •  一向
    一向 (楼主)
    2020-11-27 06:59

    As others have said, it doesn't matter, and if it does then something is wrong in your database design. But personally I just like them to be in order anyway!

    Here is some SQL that will recreate your IDs in the same order, but without the gaps.

    It is done first in a temp_id field (which you will need to create), so you can see that it is all good before overwriting your old IDs. Replace Tbl and id as appropriate.

    SELECT @i:=0;
    UPDATE Tbl
    JOIN
    (
        SELECT id
        FROM Tbl
        ORDER BY id
    ) t2
    ON Tbl.id = t2.id
    SET temp_id = @i:=@i+1;
    

    You will now have a temp_id field with all of your shiny new IDs. You can make them live by simply:

    UPDATE Tbl SET id = temp_id;
    

    And then dropping your temp_id column.

    I must admit I'm not quite sure why it works, since I would have expected the engine to complain about duplicate IDs, but it didn't when I ran it.

提交回复
热议问题