【问题标题】:How do I query for all the nodes between two nodes in a tree?如何查询树中两个节点之间的所有节点?
【发布时间】:2011-05-04 14:24:02
【问题描述】:

我有一个分层数据库结构,例如为每一行定义的列IDPARENT_ID,顶级行具有NULL PARENT_ID

我已将此表中的所有关系展平到另一个表中,例如如果祖父母、父母、孙子的单个层次结构中有 3 条记录,则将有 3 条记录:

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

与其执行分层查询来确定孙子是祖父的后代,我可以简单地检查此扁平表中是否存在(grandparent, grandchild) 记录。

我的问题是,使用这个扁平表,我怎样才能最有效地返回两个节点之间的所有记录。使用示例,以grandparentgrandchild 作为我的参数,如何取回(grandparent, parent) 记录。

我不想使用分层查询来解决这个问题...我想知道是否可以在没有任何连接的情况下执行此操作。

【问题讨论】:

  • 想必你真正的层次不限于三个层次?
  • @Renderln,您的展平表是否包含祖先和后代列,还是包含其他列(例如代数/级别数)?另外,是否有多种方法可以将一个后代链接到同一个祖先?
  • @Ed Harper:是的,这个表包含多个不同级别的层次结构。
  • @Mark Ba​​nnister:每条记录都包含祖先节点和后代节点彼此分开的跳数。它还指定该层次结构的根节点。它不包含层次结构的总高度。每个祖先可以有多个后代,但一个后代只能有一个父母。

标签: sql hierarchical-data hierarchical-trees hierarchical-query transitive-closure-table


【解决方案1】:
SELECT  *
FROM    mytable
WHERE   descendant = @descendant
        AND hops < 
        (
        SELECT  hops
        FROM    mytable
        WHERE   descendant = @descendant
                AND ancestor = @ancestor
        )

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

(descendant, hops) 上创建一个索引以使其快速工作。

【讨论】:

    【解决方案2】:

    试试:

    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
    

    【讨论】:

      【解决方案3】:
      SELECT
         distinct ancestor 
      FROM 
         hierarchy 
      WHERE descendant = :1 AND 
            ancestor IN (
                          SELECT 
                             distinct descendant 
                          FROM 
                             hierarchy WHERE ancestor = :2
                        )
      

      【讨论】:

        猜你喜欢
        • 2019-04-10
        • 1970-01-01
        • 2011-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-19
        • 2012-03-21
        相关资源
        最近更新 更多