【问题标题】:Modified Pre-order Tree Traversal, Retrieve only n levels deep?修改前序树遍历,只检索 n 层深?
【发布时间】:2012-08-28 11:04:07
【问题描述】:

我刚刚开始使用这个算法,它确实是一个很棒的方法。我唯一遇到的问题是我如何才能只检索树中的 n 个级别,例如...

Img src = http://www.sitepoint.com/hierarchical-data-database-2/(很棒的文章)

在上图中,我如何选择 Food 的所有子项,但只有 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`

【问题讨论】:

  • 添加一个额外的列来存储每个记录在树中的深度,然后你只需要添加到你的WHERE 子句AND treeItems.depth &lt;= 2
  • @eggyal :我希望我只能使用 left 和 right 值,添加额外的列将是额外的维护开销。

标签: mysql tree treeview


【解决方案1】:

我在 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

【讨论】:

    猜你喜欢
    • 2011-12-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2016-07-14
    • 2012-04-13
    • 1970-01-01
    相关资源
    最近更新 更多