Question

I have 2 tables in oracle DB: Items and Relationship.

items:

ID   
---
1
2
3
4
5
6
7

relationship:

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

In the relationship table, I'm storing the hierarchial structure of the "items" (do not ask why it's stored in different tables).

The question:

When I execute this query:

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;

I do not see the root parent because he doesn't exist in this table as a child.

The question is how can I add the root parent(ID = 1) to the query result or join it whith the "items" table and keep the result columns (level and isleaf).

Était-ce utile?

La solution

  1. CONNECT_BY_ISLEAF works the other way around when using bottom up search (see this link http://technology.amis.nl/2009/11/14/oracle-11gr2-alternative-for-connect_by_isleaf-function-for-recursive-subquery-factoring-dedicated-to-anton/)
  2. I assume that you want to show more data about the item (like name) If that is the case just left join the items table.

    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;
    

check this SQLfiddle: http://sqlfiddle.com/#!4/5c9fa/17 In addition check this post about bottom up searches (http://bitbach.wordpress.com/2010/10/18/implementing-bottom-up-path-traversal-for-hierarchical-tables/)

Autres conseils

Notice that you have both directions - parent and child. pick one and dont mix the two.

  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

connection is made by prior id = child and not prior parent = child

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top