Modified preorder tree traversal: Selecting nodes 1 level deep

我是研究僧i 提交于 2019-12-06 08:35:13

问题


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!


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!