tags:

views:

30

answers:

1

I have a tree in my database described using id and parend id. Because of historical( original programmer) reasons the id is strings. I need to convert the id to auto increment integer field and keep the structure the same. How do I do that?
I'm using mysql.

+1  A: 
  1. Add your new primary key, auto-increment numerical column. For the purposes of this exercise we shall call it "new_id" (Don't make it the primary key yet). This will automatically be filled with values, as soon as it is added, since it is auto-increment.
  2. Add another, numerical column for the new parent_id, which for now we shall call "new_parent_id".
  3. Now update the "new_parent_id" column with the correct values, using
    UPDATE my_table as t1, my_table as t2, set t1.new_parent_id = t2.new_id where t2.id = t1.parent_id
  4. Finally, drop the old primary key and make "new_id" your new primary key. If you use InnoDB, you should also make "new_parent_id" a foreign key for primary key.
  5. Drop the old "id" and "parent_id" columns and rename the new columns to the old names.
wolfgangsz
I didn't know joins work in `UPDATE`
Dani
Well, we all learn something new every day.
wolfgangsz