I have hierarchical ordered data saved using the modified preorder tree traversal algorithm.
Here's tables content:
id lft rgt name
1 1 10 topnode
2 2 3 level1
3 4 7 level1
4 5 6 level2
5 8 9 level1
Visualised:
What I want is to select just the childnodes of a certain node (so not the childnodes of the childnodes). Let's say 'topnode'. I'm trying to fix a query, but I can't seem to get my head around it.
Searching the internet brings me a while, for example: I can calculate the depth of each node, but I just can't seem to select on it.
This query
SELECT node.*, (COUNT(parent.id) - 1) AS depth
FROM tree AS node
CROSS JOIN tree AS parent
WHERE (node.lft BETWEEN parent.lft AND parent.rgt)
GROUP BY node.id
ORDER BY node.lft
shows the depth of each node:
id lft rgt name depth
1 1 10 topnode 0
2 2 3 level1 1
3 4 7 level1 1
4 5 6 level2 2
5 8 9 level1 1
That's great, but I can't use the column depth as a condition!
I think this should do the trick
SELECT node.*, (COUNT(parent.id) - 1) AS depth
FROM tree AS node
CROSS JOIN tree AS parent
WHERE (node.lft BETWEEN parent.lft AND parent.rgt)
GROUP BY node.id
HAVING depth = {{ENTER YOUR REQUIRED DEPTH HERE}}
ORDER BY node.lft
Hope that helps
来源:https://stackoverflow.com/questions/7661913/modified-preorder-tree-traversal-selecting-nodes-1-level-deep