通过事先获取 parents 和 children 连接

Connect by prior get parents and children

我正在处理一个使用 connect by prior 的查询。 我写了一个查询来检索一个实体的所有 children。我想要的是检索 children 和 parents 行。

这是我的 SQL :

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

如何检索 parents? 谢谢

使用 UNION ALL 组合查询以获取子代与另一个查询以获取祖先。

SQL Fiddle

Oracle 11g R2 架构设置:

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;

查询 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 |

如果您使用的是 11gR2 或更高版本,分层查询的另一种方法是 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;

主播成员找到了您的初始目标行。然后递归成员查找目前找到的每一行的父 子。

最终查询可以获取任何你想要的列,做聚合等等

(当然,可能值得用真实数据测试这两种方法,看看是否存在性能差异)。