I have a table with the following columns: group_id, parent_id, name
In this table parent_id is the group_id of another record. There is a 1 to N relationship of parents to children. This forms a hierarchy with only one top level group having NULL for a parent_id. There could be an arbitrary amount of depth, but in practice my hierarchy is never more than 20 levels deep.
I would like to retrieve every ancestor (a parent’s parent and so on) of a group with a given group_id. I am concerned about the particular way this is returned.
I am using MS SQL 2005, but I am also interested in solutions using other RDBMSs.
I have found some similar questions, but they all seem to break down to recursion, looping or nested sets. I cannot use nested sets, because I cannot change the data structure. I would like to avoid recursion or looping where possible, or at least understand why it is not possible.
Here are some question I found while researching this:
The operation is inherently looped. Because each node does not have any finite relation to their root, you must traverse in order to discover it.
If, for example, you knew that there was a maximum depth of N then you could create N
LEFT OUTER JOINs in a single statement and display the last non-null parent ID returned this way.The looping requirement is that you simply don’t know what N is, and you cannot ask a declarative language like SQL to “figure it out”
Even if you can accomplish it with some built-in method, it will still be a loop or recursion, just obfuscated from you.