我在oracle DB中有两个表:Item和Relationship。
项目:
ID
---
1
2
3
4
5
6
7
关系:
ID parent child
--------------------
1 1 2
2 1 3
3 1 4
4 2 5
5 2 6
6 3 7
在relationship表中,我要存储"items“的层次结构(不要问它为什么存储在不同的表中)。
问题是:
当我执行这个查询时:
SELECT PARENT_ID, CHILD_ID, CONNECT_BY_ISLEAF, MAX(LEVEL) OVER () + 1 - LEVEL as rev_level
FROM relationship
CONNECT BY PRIOR PARENT_ID = CHILD_ID
START WITH CHILD_ID = 7;
我没有看到根父级,因为它作为子表不存在于此表中。
问题是如何将根父(ID= 1)添加到查询结果中,或者如何使用"items“表将其连接起来,并保留结果列(level和isleaf)。
发布于 2014-01-06 08:16:11
CONNECT_BY_ISLEAF
的工作方式正好相反(参见此链接isleaf-function-for-recursive-subquery-factoring-dedicated-to-anton/)。检查这个SQLfiddle:http://sqlfiddle.com/#!4/5c9fa/17,另外检查这篇关于自下而上搜索的文章(http://bitbach.wordpress.com/2010/10/18/implementing-bottom-up-path-traversal-for-hierarchical-tables/)
发布于 2014-01-06 07:23:50
注意,你有两个方向--父母和孩子。选一个,不要把两者混在一起。
1 with x as (
2 select 1 as id, 1 as parent, 2 as child from dual union all
3 select 2, 1 , 3 from dual union all
4 select 3 ,1, 4 from dual union all
5 select 4 ,2, 5 from dual union all
6 select 5 ,2, 6 from dual union all
7 select 6 ,3, 7 from dual)
8 select *
9 from x
10 sTART WITH child = 7
11* CONNECT BY PRIOR id= CHILD
SQL> /
ID PARENT CHILD
---------- ---------- ----------
6 3 7
5 2 6
4 2 5
3 1 4
2 1 3
1 1 2
连接是由prior id = child
而不是prior parent = child
创建的。
https://stackoverflow.com/questions/20944837
复制相似问题