开发者

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.


  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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜