Wednesday, July 15, 2009

Queries for Nested Set Model

So this is just a follow up post to my Nested Set Model post to document the scheme/queries that I'm using to define my tree. I created a node with id=0 called ROOT (since it's basically just a place holder that I use to do the dirty work and won't ever show the user) and create a UNIQUE constraint on (lft, rgt) to satisfy my obsession with data integrity (and I imagine that it should help speed up the queries as well).

So here's the queries I use to grab the information in useful manners.

Grab the Whole Tree:
SELECT *
FROM bills
ORDER BY lft;
Grabs the Ancestors of a Node:
SELECT parent.*
FROM bills AS node, bills AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.id = ? AND parent.id <> ? (NOTE: Both ?'s are the same value)
ORDER BY node.lft;
Grabs the Descendents of a Node:
SELECT node.*
FROM bills AS node, bills AS parent
WHERE node.lft > parent.lft AND node.rgt < id =" ?">
Grab the Parent of a Node:
SELECT parent.*
FROM bills AS node, bills AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.id = ?
ORDER BY parent.lft DESC LIMIT 1,1
Obviously, the '?' is the ID of the node that you're interested in and you can cater the selected columns to your needs.

No comments: