Return all nodes in many-to-many hierarchal tree

前端 未结 2 1192
暗喜
暗喜 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:26

    Since you need to model data where nodes can have multiple parents, a nested set/MPTT solution will not work. Another alternative is the use of a closure table.

    You would create an additional table that held pairs of items for every ancestor's descendant (and vice versa):

    AncID  DesID
      1      2
      1      6
      1      4
      1      8
      1      7
      1      3
      1      5
      1      9
      2      4
      2      8
      2      3
      2      5
      2      9
      4      3
      4      5
      4      9
      3      5
      3      9
      6      7
    

    Then you would use a join to get the items you need:

    SELECT * 
    FROM Tbl INNER JOIN Closure ON Tbl.ID=Closure.DesID 
    WHERE Closure.AncID = 2
    

提交回复
热议问题