简体   繁体   English

通过事先得到父母和孩子的联系

[英]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 : 这是我的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. 使用UNION ALL组合一个查询来获得子项,再通过一个查询来获得祖先。

SQL Fiddle SQL小提琴

Oracle 11g R2 Schema Setup : 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;

Query 1 : 查询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 : 如果您使用的是11gR2或更高版本,则分层查询的另一种方法是递归子查询分解

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). (当然,可能值得用真实数据测试这两种方法,以查看是否存在性能差异)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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