views:

45

answers:

3

In mysql, I have a tree that is represented using the adjacency list model.

MYTREE
   id
   parent_id
   title

I am wondering:

Given the id of a node, is there any way to SELECT the entire tree beneathe that node, complete with depth information? The tree is arbitrarily deep, so I cannot say how many levels there may be. But the resultset might look something like this:

ID      TITLE     DEPTH
4       title1    1
8       title2    2
16      title8    3
9       title3    2
15      title4    3

I know that it is possible to do this using the nested sets model. But there are things about nested sets that are not ideal, and I'm hoping not to have to switch over.

Thanks for the advice!

A: 

Short answer: no.

The only way to traverse a tree represented with parent pointers is to follow one set of parent IDs after the next. That's possible if you can limit the depth, by simply joining that many times across the table, but with an unlimited depth an application-side loop is generally the way to go.

VoteyDisciple
parent/child isn't the only way do store hierarchal data... the nested set model works quite flexibly in this regard..
Dan Heberden
Travis acknowledged that in the original post. I'm addressing specifically the question of whether it can be done with parent pointers.
VoteyDisciple
A: 

EDIT: I didn't notice the arbitrarily deep clause in the title:

You could write a Stored Procedure to recurse over the rows.

But what's not ideal about Nested Sets (at least that couldn't be taken care of by a before insert trigger or a stored procedure)?

ircmaxell
Modifications to the tree - like the addition of a node - rewrite left and right values for large #s of rows. I'm concerned about scalability.
Travis
How many inserts are you doing? I have a tree in InnoDB that has around 2.5 million nodes. I do batch inserts (around 500k at a time), and the insert process takes all of maybe 10 seconds (for all 500k). It's updating the tree each insert off of a before insert trigger, so unless you're doing BOAT loads of writes (hundreds to thousands per second), I wouldn't really worry about it (personally)...
ircmaxell
Good to hear that you have had success using nested sets under that much load. My requirements are not nearly as heavy.
Travis
A: 

Here is a blog post I wrote about one way to approach this problem:

http://nathansnoggin.blogspot.com/2009/10/storing-tree-structure-in-database.html

nathan