简体   繁体   中英

Connect by prior get parents and children

I'm working on a query which use connect by prior. I have written a query which retrieves all children of an entity. What I want is to retrieve both children and parents rows.

Here is my SQL :

Select *
From myTable tab
Connect By Prior tab.id= tab.child_id
Start With tab.id= 2;

How could I retrieve parents ? Thanks.

Use UNION ALL to combine a query to get the children with another to get the ancestors.

SQL Fiddle

Oracle 11g R2 Schema Setup :

CREATE TABLE myTable ( id, child_id ) AS
SELECT 0, 1 FROM DUAL UNION ALL
SELECT 1, 2 FROM DUAL UNION ALL
SELECT 2, 3 FROM DUAL UNION ALL
SELECT 3, 4 FROM DUAL UNION ALL
SELECT 4, 5 FROM DUAL UNION ALL
SELECT 3, 6 FROM DUAL UNION ALL
SELECT 0, 7 FROM DUAL UNION ALL
SELECT 1, 8 FROM DUAL;

Query 1 :

SELECT *                        -- Child Rows
FROM   mytable
START WITH id = 2
CONNECT BY PRIOR child_id = id
UNION ALL
SELECT *                        -- Ancestor Rows
FROM   mytable
START WITH child_id = 2
CONNECT BY PRIOR id = child_id

Results :

| ID | CHILD_ID |
|----|----------|
|  2 |        3 |
|  3 |        4 |
|  4 |        5 |
|  3 |        6 |
|  1 |        2 |
|  0 |        1 |

An alternative approach to a hierarchical query, if you're on 11gR2 or higher, is recursive subquery factoring :

with rcte (id, child_id, some_other_col) as (
  select id, child_id, some_other_col -- whichever columns you're interested in
  from myTable
  where id = 2
  union all
  select t.id, t.child_id, t.some_other_col  -- whichever columns you're interested in
  from rcte r
  join myTable t
  on t.id = r.child_id -- match parents
  or t.child_id = r.id -- match children
)
cycle id set is_cycle to 1 default 0
select id, child_id, some_other_col  -- whichever columns you're interested in
from rcte
where is_cycle = 0;

The anchor member finds your initial target row. The recursive member then looks for parents or children of each row found so far.

The final query can get whichever columns you want, do aggregation, etc.

(Possibly worth testing both approaches with real data to see if there is a performance difference, of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM