【问题标题】:Joining other tables in oracle tree queries在 oracle 树查询中连接其他表
【发布时间】:2010-09-12 03:55:19
【问题描述】:

给定一个简单的(id,description)表t1,比如

id  description
--  -----------
1   Alice
2   Bob
3   Carol
4   David
5   Erica
6   Fred

还有一个父子关系表t2,比如

parent  child
------  -----
1       2
1       3
4       5
5       6

Oracle 提供了一种将其作为具有一些自定义语法扩展的树来遍历的方法:

select parent, child, sys_connect_by_path(child, '/') as "path"
from t2
connect by prior parent = child

确切的语法并不重要,我可能在上面犯了一个错误。这 重要的是上面会产生一些看起来像

parent  child  path
------  -----  ----
1       2      /1/2
1       3      /1/3
4       5      /4/5
4       6      /4/5/6
5       6      /5/6

我的问题是:是否可以在 sys_connect_by_path() 中加入另一个表,例如上面的 t1 表,以产生类似:

parent  child  path
------  -----  ----
1       2      /Alice/Bob
1       3      /Alice/Carol
... and so on...

【问题讨论】:

    标签: sql oracle tree connect-by


    【解决方案1】:

    在您的查询中,将 T2 替换为连接 T1 和 T2 并返回父、子和子描述的子查询。然后在 sys_connect_by_path 函数中,引用子查询中的子描述。

    【讨论】:

      【解决方案2】:

      基于 Mike McAllister 的想法,下面使用派生表来达到想要的结果:

      select
           T.PARENT
          ,T.CHILD
          ,sys_connect_by_path(T.CDESC, '/')
      from
          (
              select
                   t2.parent      as PARENT
                  ,t2.child       as CHILD
                  ,t1.description as CDESC
              from
                   t1, t2
              where
                  t2.child = t1.id
          ) T
      where
          level > 1 and connect_by_isleaf = 1
      connect by prior
          T.CHILD = T.PARENT
      

      在我的问题中,所有的父母都锚定在一个“超级父母”根下,这意味着路径可以用 SYS_CONNECT_BY_PATH 完全描述,从而消除了对 cagcowboy 将父母与路径连接起来的技术的需要。

      【讨论】:

      • 好东西,感谢您将您的解决方案放在这里。我希望更多的人会这样做,它可以帮助下一个来到 StackOverflow 寻找这个答案的人。
      • 很好地使用了obviate这个词! :-)
      【解决方案3】:
      SELECT parent, child, parents.description||sys_connect_by_path(childs.description, '/') AS "path"
      FROM   T1 parents, T1 childs, T2
      WHERE  T2.parent = parents.id
      AND    T2.child = childs.id
      CONNECT BY PRIOR parent = child
      

      【讨论】:

      • 那不太行。在多级层次结构的情况下,路径不正确。例如 David/Fred/Erica 而不是 David/Erica/Fred
      猜你喜欢
      • 2011-09-11
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2018-11-03
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多