我刚开始使用这个算法,它确实是一个很棒的方法。我唯一坚持的是如何只检索树中深层的n个级别,例如......
Img src = http://www.sitepoint.com/hierarchical-data-database-2/(伟大文章)
在上图中,我如何选择食物的所有孩子,但只有2级深入树(除了樱桃和香蕉之外的所有东西)。
您只需要使用伪代码回答,但如果您愿意,可以使用MySQL。
我当前的SQL查询如下所示:
SELECT `treeItems`.`ID` AS `treeItemsID`, `treeItems`.`parent`, `treeItems`.`type`
FROM
`treeItems`,
(
SELECT `lft`, `rgt` FROM `treeItems` WHERE `ID` = $parent
) AS `parentRow`
WHERE `treeItems`.`lft` > `parentRow`.`lft` AND `treeItems`.`lft` < `parentRow`.`rgt`
答案 0 :(得分:3)
我在SO上找到了另一个类似的问题:Modified preorder tree traversal: Selecting nodes 1 level deep,这有助于我解决它。
所以,我把我的SQL改为:
SELECT `treeItems`.*, (COUNT(`depthJoin`.`ID`) - 1) AS `depth`
FROM `treeItems`,
(
SELECT `lft`, `rgt` FROM `treeItems` WHERE `ID` = $parent
) AS `parentRow`
CROSS JOIN `treeItems` AS `depthJoin`
WHERE (`treeItems`.`lft` BETWEEN `depthJoin`.`lft` AND `depthJoin`.`rgt`)
AND (`treeItems`.`lft` > `parentRow`.`lft` AND `treeItems`.`lft` < `parentRow`.`rgt`)
GROUP BY `treeItems`.`ID`
HAVING `depth` <= $maxDepth