Fetching linked list in MySQL database

后端 未结 3 1777
孤街浪徒
孤街浪徒 2020-11-29 08:06

I have a MySQL database table with this structure:

table
    id INT NOT NULL PRIMARY KEY
    data ..
    next_id INT NULL

I need to fetch t

3条回答
  •  迷失自我
    2020-11-29 08:12

    If what you are trying to avoid is having several queries (one for each node) and you are able to add columns, then you could have a new column that links to the root node. That way you can pull in all the data at once by the root id, but you will still have to sort the list (or tree) on the client side.

    So in this is example you would have:

     id | next_id | root_id
    ----+---------+---------
      1 |       2 |       1
      2 |       4 |       1
      3 |       9 |       1
      4 |       3 |       1
      9 |    NULL |       1
    

    Of course the disadvantage of this as opposed to traditional linked lists or trees is that the root cannot change without writing on an order of magnitude of O(n) where n is the number of nodes. This is because you would have to update the root id for each node. Fortunately though you should always be able to do this in a single update query unless you are dividing a list/tree in the middle.

提交回复
热议问题