我在oracle DB中有2个表:项目和关系。
项目:
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
在关系表中,我存储了“项目”的层次结构(不要问为什么它存储在不同的表中)。
问题:
执行此查询时:
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)。
答案 0 :(得分:0)
请注意,您有两个方向 - 父母和孩子。 选一个,不要混合两个。
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
答案 1 :(得分:0)
CONNECT_BY_ISLEAF
可以反过来工作(请参阅此链接http://technology.amis.nl/2009/11/14/oracle-11gr2-alternative-for-connect_by_isleaf-function-for-recursive-subquery-factoring-dedicated-to-anton/)我假设您想要显示有关该项目的更多数据(如名称)如果是这种情况,只需左边加入项目表。
SELECT PARENT_ID AS PARENT_ID,CHILD_ID, i.name AS CHILD_NAME,
CONNECT_BY_ISLEAF,
MAX(LEVEL) OVER () + 1 - LEVEL AS rev_level
FROM items i
LEFT JOIN relationship r ON (i.id = r.CHILD_ID)
CONNECT BY PRIOR PARENT_ID = CHILD_ID
START WITH CHILD_ID = 7
ORDER BY REV_LEVEL;
检查这个SQLfiddle:http://sqlfiddle.com/#!4/5c9fa/17 另外,请查看有关自下而上搜索(http://bitbach.wordpress.com/2010/10/18/implementing-bottom-up-path-traversal-for-hierarchical-tables/)
的帖子