How to re-assign AUTO_INCREMENT column for every row in a MySQL table using PHP

后端 未结 4 1903
傲寒
傲寒 2020-12-31 09:55

I have an image gallery which website members can upload images to. When an image is uploaded, a MySQL row is written, containing various pieces of information about the ima

4条回答
  •  情深已故
    2020-12-31 10:23

    If you want the auto-incrementing id's to always be consecutive, let it go, it's a useless struggle.

    If you just want to renumber once, that's easy:

    Create a new table with the same layout:

    CREATE TABLE mytable2 LIKE oldtable;
    

    Copy all rows to the new table, remember to not select the auto_incrementing id, otherwise the old numbering will be retained.

    INSERT INTO mytable2 (field2, field3, field4)
      SELECT field2, field3, field4 FROM oldtable ORDER BY oldtable.id;
    
    RENAME oldtable archive;
    
    RENAME mytable2 oldtable;
    
    DROP archive;
    

    You now have consecutive numbering.

提交回复
热议问题