先与父母和孩子联系

时间:2018-01-29 13:07:44

标签: sql oracle connect-by

我正在处理一个使用先前连接的查询。 我编写了一个查询来检索实体的所有子项。我想要的是检索子行和父行。

这是我的SQL:

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

我怎样才能找回父母? 感谢。

2 个答案:

答案 0 :(得分:3)

使用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 |

答案 1 :(得分: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;

锚点成员找到您的初始目标行。然后递归成员查找到目前为止找到的每行的父子项。

最终查询可以获得您想要的任何列,进行聚合等。

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