I have a tree structure that can be n-levels deep, without restriction. That means that each node can have another n nodes.
What is the best way to retrieve a tree like that without issuing thousands of queries to the database?
I looked at a few other models, like flat table model, Preorder Tree Traversal Algorithm, and so.
Do you guys have any tips or suggestions of how to implement a efficient tree model? My objective in the real end is to have one or two queries that would spit the whole tree for me.
With enough processing i can display the tree in dot net, but that would be in client machine, so, not much of a big deal.
Oh just dropping some more info here:
environment: Oracle or PostgreSQL, C# and Winforms.
Thanks for the attention
Assuming your only concern is selects and not inserts/updates/deletes, this depends on needs, such as:
However, if there really are minimal changes to the tree being done, then it almost doesn’t matter what scheme you use, as you can do all the work in the application layer and cache the output.
Edit:
When order matters, I usually go for the materialized path method, and add an additional column SortPath. This way you can get your results sorted by sibling, which is a denormalization that makes rendering the tree in HTML extremely easy, as you can write out the entire tree (or any portion) in exactly the order you receive the records using a single query. This is optimal for speed, and is the easiest way to sort more than one level at a time.
E.g.,
Output:
You can determine the level of each node by counting pipes (or periods) in the application layer, or in SQL using whatever built-int or custom functions that can count occurrences of a string.
Also, you’ll notice I append the
IDto theNamewhen buildingSortPath. This is to ensure that two sibling nodes with the same name will always get returned in the same order.