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.
views:
30answers:
1
+1
A:
- 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.
- Add another, numerical column for the new parent_id, which for now we shall call "new_parent_id".
- 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
- 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.
- Drop the old "id" and "parent_id" columns and rename the new columns to the old names.
wolfgangsz
2010-08-19 08:04:45
I didn't know joins work in `UPDATE`
Dani
2010-08-19 08:09:53
Well, we all learn something new every day.
wolfgangsz
2010-08-19 16:26:53