This is how I did it
I have a table called Events
that has these fields where the id
field is primary key and auto incremented:
id
EventType
DateTime
Weight
Comment
To 're-index' the table I did things in this order:
- Created new table based on old tables structure
- Copy records into new table WITHOUT the id field from old table, sorting by old tables id field
- Drop old table
- Rename new table to old table name
Like this:
CREATE TABLE NewEvents LIKE Events;
INSERT INTO NewEvents (EventType, DateTime, Weight, Comment) SELECT EventType, DateTime, Weight, Comment FROM Events ORDER BY id;
DROP TABLE Events;
RENAME TABLE NewEvents TO Events;
The second command that copies the records over to the new table is what re-creates the new index numbers. And because the records are sorted by the id field of the old table, it will ignore any missing id numbers and just keep auto-incrementing the new tables id field.
It worked for me anyways, but I highly recommend testing this from a complete copy of the entire schema then testing with your app to make sure everything works properly before doing this on a live / production schema.
I've never used TRIGGERS before, so I'm not sure if creating a table that is LIKE another table actually re-creates the triggers or not., nor am I sure if it re-creates any foreign key relationships. My gut says that these things will NOT be re-created, but in my case, this didn't matter. The point is, don't do this haphazardly - TEST TEST TEST on non-production data before doing this and BE THOROUGH!