【问题标题】:Query to get child records of given parent id查询以获取给定父 ID 的子记录
【发布时间】:2021-02-12 08:37:07
【问题描述】:

我有一个查询要从 Table2 中查找子数据,这些子数据具有在其他表中定义的分层数据,即 oracle 中的 TABLE1。

表1

ID, CHILD_ID, PARENT_ID
1,  1           
2,  2,      1   
3,  3,      2   
4,  4,      3   
5,  5,      4   
6,  6,      4   
7,  7,      4   
8,  8,      5   
9,  9,      5   

表2

NAME,AGE,ID
JJ,22,1
XX,19,2
YY,20,3
KK,21,4
PP,18,5
CC,19,6
DD,22,7
SS,44,8
QQ,33,9

当我查询 ID 7 时,输出应该

NAME,AGE,ID
DD,22,7

因为没有 7 的孩子

当我查询 5 时,它应该在下面显示为 8 和 9 是 5 的孩子

NAME,AGE,ID
PP,18,5
SS,44,8
QQ,33,9

请建议,提前致谢

【问题讨论】:

  • 是只有一层的父子关系,还是需要检查子节点的子节点等等?

标签: sql oracle inner-join recursive-query


【解决方案1】:

您可以执行以下操作来处理一般情况(即不仅会得到父母和孩子,而且可能会得到孩子的孩子等等)。

with thevalues as
(
 SELECT child, parent
 FROM table1 
 START WITH parent=4
 CONNECT BY PRIOR child = parent
)
SELECT *
FROM table2
WHERE id IN (SELECT child FROM thevalues UNION ALL SELECT parent FROM thevalues)

其中parent=4 定义起始记录。 Connect By 用于这些分层查询。

虽然上面的例子也适用于你的例子中的简单情况,但如果你不关心孩子的孩子,你可能更喜欢类似的东西

SELECT *
FROM table2
WHERE id=4
UNION ALL
SELECT *
FROM table2
WHERE id IN
(
 SELECT child
 FROM table1
 WHERE parent=4
)

请注意,在此示例中,我在两个地方硬编码了 4。

【讨论】:

  • 是的,我还需要一个孩子的孩子,以及一个完美地根据需要获取数据的孩子
【解决方案2】:

如果你只想要直接的孩子,那么exists 子查询就足够了:

select t2.*
from table2 t2
where exists (
    select 1 from table1 t1 where t1.child_id = t2.id and 5 in (t1.child_id, t1.parent_id)
)

或者:

select t2.*
from table2 t2
where t2.id = 5 or exists (
    select 1 from table1 t1 where t1.child_id = t2.id and t1.parent_id = 5
)

另一方面,如果您想要所有孩子,无论他们的级别如何,那么我建议使用递归查询:

with cte (child_id, parent_id) as (
    select child_id, parent_id from table1 where child_id = 5
    union all
    select t1.child_id, t1.parent_id
    from cte c
    inner join table1 t1 on t1.parent_id = c.child_id
)
select t2.*
from table2 t2
where exists (select 1 from cte c where c.child_id = t2.id)

【讨论】:

    【解决方案3】:

    您可以使用这样的查询来找到合适的孩子。只需将您在 CONNECT_BY_ROOT (t1.id) = 5 子句中搜索的 ID 从 5 更改为任何 ID,它应该可以按预期工作。

        SELECT t2.name, t2.age, t1.id
          FROM table1 t1, table2 t2
         WHERE t1.id = t2.id AND CONNECT_BY_ROOT (t1.id) = 5
    CONNECT BY PRIOR t1.id = t1.parent_id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多