帮助编写嵌套集的SQL查询

前端之家收集整理的这篇文章主要介绍了帮助编写嵌套集的SQL查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用嵌套集将数据库存储在数据库中.表的字段是id,lft,rgt和name.

给定一个节点ID,我需要找到它们自己的叶子节点的所有直接子节点(不是孙子节点).

解决方法

文章 Managing Hierarchical Data in MySQL给出了如何使用嵌套集的一个很好的例子,并给出了许多常见查询的示例,包括这一个.

这是如何找到节点的直接子节点:

SELECT node.name,(COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,nested_category AS parent,nested_category AS sub_parent,(
        SELECT node.name,(COUNT(parent.name) - 1) AS depth
        FROM nested_category AS node,nested_category AS parent
        WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND node.name = '**[[MY NODE]]**'
        GROUP BY node.name
        ORDER BY node.lft
    )AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
    AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
    AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth = 1
ORDER BY node.lft;

然后将它与叶子节点的rgt等于lft 1这一事实相结合,然后进行设置.原谅双关语.

原文链接:https://www.f2er.com/mssql/83568.html

猜你在找的MsSQL相关文章