Return all nodes in many-to-many hierarchal tree

前端 未结 2 1216
暗喜
暗喜 2021-01-27 10:11

Similar to this question: How do I query for all the nodes between two nodes in a tree?

But I do not have a closure (flattened) table, a child can have many par

2条回答
  •  一整个雨季
    2021-01-27 10:15

    For SQL Server: Adjacency list vs. nested sets: SQL Server

    For Jet/MS Access, recursive queries are not an option, so nested sets would be the way to go. For a sample: http://www.mvps.org/access/queries/qry0023.htm

    Some background on nested sets:

    To implement a nested set solution you would need to add and maintain two additional columns in your table: Lt and Rt(left and right, respectively). You populate these columns by executing a modified preorder tree traversal to assign values to these columns. This can be done most easily with a recursive function. You can then use the left and right values to determine descendants at SELECT time.

    The tradeoff is more processing required whenever data is changed but much faster execution when data is retrieved.

    The concept is somewhat non-intuitive and certainly has a learning curve, but I have personally used it to great effect. As far as I know, it is the only way to accomplish what you are after using only SELECT queries in Jet (the MS Access db engine).

    Sample Nested Set Solution:

    ParentID    ID  Lt  Rt  RowNumber(Reference)
    Null        1    1  18  0
    1           2    2  13  1
    2           4    3  10  2
    4           3    4   9  3
    3           5    5   6  4
    1           6   14  17  5
    6           7   15  16  6
    2           8   11  12  7
    3           9    7   8  8
    

    Then to get all descendants of ID 2:

    SELECT * FROM Tbl WHERE Lt Between 2 And 13
    

    Here's what the tree looks like graphically:

    Modified Preorder Tree

提交回复
热议问题