[英]Modified preorder tree traversal: Selecting nodes 1 level deep
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'. 让我们说'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 希望有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.