在oracle树查询中加入其他表

dla*_*and 8 sql oracle tree connect-by

给出一个简单的(id,description)表t1,例如

id  description
--  -----------
1   Alice
2   Bob
3   Carol
4   David
5   Erica
6   Fred
Run Code Online (Sandbox Code Playgroud)

和父子关系表t2,如

parent  child
------  -----
1       2
1       3
4       5
5       6
Run Code Online (Sandbox Code Playgroud)

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

select parent, child, sys_connect_by_path(child, '/') as "path"
from t2
connect by prior parent = child
Run Code Online (Sandbox Code Playgroud)

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

parent  child  path
------  -----  ----
1       2      /1/2
1       3      /1/3
4       5      /4/5
4       6      /4/5/6
5       6      /5/6
Run Code Online (Sandbox Code Playgroud)

我的问题是:是否可以在sys_connect_by_path()中连接另一个表,例如上面的t1表,以生成类似于:

parent  child  path
------  -----  ----
1       2      /Alice/Bob
1       3      /Alice/Carol
... and so on...
Run Code Online (Sandbox Code Playgroud)

Mik*_*ter 7

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


dla*_*and 6

基于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
Run Code Online (Sandbox Code Playgroud)

在我的问题中,所有父节点都锚定在"超父"根下,这意味着可以使用SYS_CONNECT_BY_PATH完全描述路径,从而避免了使用cagcowboy将父节点与路径连接的技术.