質問

I have a table with such rows:

    ID        Parent_ID   Name
    1         (null)      A
    2         1           B
    3         1           C
    4         2           D
    5         3           E
    6         5           F
    7         (null)      G
    8         (null)      H

I need to get IDs of all related rows no matter if Name='A' or 'F' is passed as criteria. In this case I should receive all ID beside 7 and 8.

I tried lot of examples and read a lot of articles but I give up now. Can you help with it?

役に立ちましたか?

解決

with
   t as (
      select id
      from your_table
      where name = 'D'  -- your starting point
   )
select id
from (
   select id, parent_id from your_table
   where parent_id is not null
   union all
   select parent_id, id from your_table
   where parent_id is not null
   union all
   select id, null from t
)
start with parent_id is null
connect by nocycle prior id = parent_id

fiddle

他のヒント

A is at the root of a hierarchy (it's the parent of B, which is the parent of D, etc.). To start with A and work down to F (and also down to D and E, which also have A as a parent through different routes):

SELECT ID, Parent_ID, Name
FROM tbl
START WITH Name = 'A'
CONNECT BY PRIOR ID = Parent_ID

F is at the end of a hierarchy. Oracle calls this a "leaf". To start with leaf F and work up to A at the top:

SELECT ID, Parent_ID, Name
FROM tbl
START WITH Name = 'F' -- start with F instead of A
CONNECT BY PRIOR Parent_ID = ID -- switch the CONNECT BY to work up

Oracle has a SYS_CONNECT_BY_PATH function that's great for visualizing the hierarchy. Here's how to use it in the first query (A down to F):

SELECT ID, Parent_ID, Name, SYS_CONNECT_BY_PATH(Name, '/') AS Path
FROM tbl
START WITH Name = 'A'
CONNECT BY PRIOR ID = Parent_ID

Results:

  ID  PARENT_ID NAME PATH
---- ---------- ---- -----------
   1            A    /A
   2          1 B    /A/B
   4          2 D    /A/B/D
   3          1 C    /A/C
   5          3 E    /A/C/E
   6          5 F    /A/C/E/F

You can use any delimeter you want as the second argument to SYS_CONNECT_BY_PATH.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top