且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何查询树中两个节点之间的所有节点?

更新时间:2023-02-01 22:42:06

SELECT  *
FROM    mytable
WHERE   descendant = @descendant
        AND hops < 
        (
        SELECT  hops
        FROM    mytable
        WHERE   descendant = @descendant
                AND ancestor = @ancestor
        )

这将自动处理@ancestor不是真正的@descendant祖先的情况.

This will automatically take care of cases when @ancestor is not really a @descendant's ancestor.

(descendant, hops)上创建索引以使其快速运行.

Create an index on (descendant, hops) for this to work fast.