3 ms·
If you need to deal with hierarchies in SQL, look into nested sets. It allows you to make a single db call to retrieve a full set of parent/child related items
by tom_b 17y ago
If you need to deal with hierarchies in SQL, look into nested sets. It allows you to make a single db call to retrieve a full set of parent/child related items.
It's basically an augmented data structure (adding a left/right value pair to the data) to allow you to query somewhat like ErrantX mentions (ie, to find the child tree of a thread with left=x and right=y, select all data where left > x and right < y). Re: deleted children, I'd just add a column to the table to store a deleted flag. You can pretty easily move comments to new parents, but have to recompute your left/right value pairs - I've done this in SQL before, it's no biggie, but I wouldn't want to be doing it in an app where I was aiming for high transaction rates (ie, human edits to threads would probably be ok, driving millions of bank transactions would not).
Joe Celko has a whole book out on hierarchies in SQL and I like it. You can find decent examples out on the web as well.