3

I'm looking for pure SQL (or MySQL) syntax and I don't know if it's possible else I will create an php script but ...

I have a basic table with one primary key : ID and somes columns. I have no dependance with others tables.

At the moment my rows look like :

ID   Column1   Column2  
22   test      test
26   test2     test2
33   test3     test3
...

Now I want to regenerate all my ID to keep order. Example: I set start at 22

ID   Column1   Column2  
22   test      test
23   test2     test2
24   test3     test3
...
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
Kakawait
  • 3,929
  • 6
  • 33
  • 60
  • possible duplicate of [MySQL: Reorder/Reset auto increment primary key?](http://stackoverflow.com/questions/740358/mysql-reorder-reset-auto-increment-primary-key) – gbn Aug 09 '11 at 08:10
  • 1
    Side note: `AUTO_INCREMENT` is not a good choice for identifiers that do have a meaning. For instance, you have to issue a DML query just to reset it. – Álvaro González Aug 09 '11 at 08:14

2 Answers2

12

Go and look there : Reorder / reset auto increment primary key

But as said there it will ruined the relationship you already have. But since you don't it's ok

ALTER TABLE `table` DROP `id`;
ALTER TABLE `table` AUTO_INCREMENT = 1;
ALTER TABLE `table` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
Community
  • 1
  • 1
yokoloko
  • 2,820
  • 3
  • 20
  • 27
1

The easiest approach would be to create a new table with your desired auto_increment column then

INSERT INTO myNewTable (column1, column2)
SELECT column1, column2
FROM myOldTable
ORDER BY ID
Code Magician
  • 23,217
  • 7
  • 60
  • 77