Easiest way to build a tree from a list of Ancestors

后端 未结 2 1898
名媛妹妹
名媛妹妹 2021-02-10 06:08

In my heart, I feel that there must be a super simple recursive solution to this, but I cannot immediately grok it.

I have a tree stored in SQL as a closure table. The

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-10 06:40

    I've used a closure table (the term sounds strange to me... I forgot what/where I heard it called something else) but I had a 3rd column of "distance" between ancestor and descendant, which lets you distinguish between direct descendants (children) and indirect descendants (grandchildren etc).

    Technically the table you listed can record data in a directed acyclic graph, so it may not be possible to construct a hierarchical tree w/o duplicate sections.

    edit:

    If I were querying in PHP, I'd probably just SELECT on the table itself w/o using GROUP_CONCAT -- you're going to be processing things procedurally anyway, so why not just get the appropriate subset of the closure table in its rawest form?

    Note also that a closure table will not store ordering information (if that is important).

    If the tree aspects of this hierarchical data are very important, and you have a choice of how to store data, consider the nested set model which can maintain ordering and is much easier to reconstruct a tree.

提交回复
热议问题