Converting string based structure to auto increment based tree structure
I have a tree in my databas开发者_StackOverflowe 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.- 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.
精彩评论