我有一个分层数据库Strucutre,例如列 IDPARENT_ID 为每行定义,顶级行有一个 NULL PARENT_ID.

我将这张桌子中的所有关系都变成了另一个表格,例如,如果有一个祖父母,父母,孙子的单个层次结构中有3个记录,则会有3个记录:

**ANCESTOR, DESCENDANT**
grantparent, parent
grandparent, grandchild
parent, grandchild

与其执行分层查询以确定孙子是祖父母的后代,我可以简单地检查存在 (grandparent, grandchild) 记录在这张平坦的桌子中。

我的问题是,使用这张扁平的表格,我如何最有效地返回两个节点之间的所有记录。使用示例,与 grandparentgrandchild 作为我的参数,我该如何恢复 (grandparent, parent) 记录。

我不想使用层次查询来解决这个问题...我想知道是否可以无需加入即可执行此操作。

有帮助吗?

解决方案

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

这将自动照顾案件 @ancestor 不是真的 @descendant的祖先。

创建一个索引 (descendant, hops) 为此快速工作。

其他提示

尝试:

select h1.descendant intermediate_node
from hierarchy h0 
join hierarchy h1 
  on h0.ancestor = h1.ancestor 
 and h0.hops > h1.hops  -- redundant condition, but may improve performance
join hierarchy h2
  on h1.ancestor = h2.ancestor 
 and h0.descendant = h2.descendant
where h0.ancestor = :ancestor and h0.descendant = :descendant
SELECT
   distinct ancestor 
FROM 
   hierarchy 
WHERE descendant = :1 AND 
      ancestor IN (
                    SELECT 
                       distinct descendant 
                    FROM 
                       hierarchy WHERE ancestor = :2
                  )
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top