在Oracle树查询中联接其他表
时间:2020-03-06 14:33:54 来源:igfitidea点击:
给定一个简单的(id,描述)表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...
解决方案
在查询中,将T2替换为连接T1和T2并返回父项,子项和子项描述的子查询。然后在sys_connect_by_path函数中,引用子查询中的子描述。
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
根据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的将父母与路径串联的技术。