Implementing a hierarchical data structure in a database

后端 未结 6 602
难免孤独
难免孤独 2020-11-29 03:32

I know there are two approaches: adjacency list and nested tree. It\'s said that adjacency list can become slow to use on traversal because of numerous queries. But I don\'t

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 04:07

    The naive approach to parsing an adjacency list requires a lot of queries, and for large lists may take a significant amount of time to build in memory. For reference, the naive approach I'm referring to could be summarized as: Select all items with no parent, Then for each item recursively get it's children. This approach requires n+1 database queries.

    I've used the following approach to build an adjacency list with 1 query. Select all items form the database. Transfer all items into an array indexed by their key. Traverse the array and assign a reference from the parent object to each of it's children. Traverse the array a second time and remove all of the child objects leaving behind only the root level objects.

    Since you mentioned LAMP stack, PHP code to do this is roughly as follows:

     $item) {
      if ($item['parent_id'] != 0 || $item['parent_id'] !== NULL) {
        $tmp[$item['parent_id']]['children'][$id] = &$tmp[$id];
      }
    }
    
    // Finally create an array with just root level items.
    $tree = array();
    foreach ($tmp as $id => $item) {
      if ($item['parent_id'] == 0 || $item['parent_id'] === NULL) {
        $tree[$id] = $item;
      }
    }
    
    // $tree now contains our adjacency list in tree form.
    ?>
    

    Please note this code is intended to illustrate a technique for building an adjacency list from a single database query. It could probably be optimized for less memory consumption, etc. It also hasn't been tested.

    Jim,

提交回复
热议问题