【问题标题】:Retrieve parent and children with connect by使用 connect by 检索父母和孩子
【发布时间】:2017-06-23 08:16:38
【问题描述】:

我有以下疑问:

  SELECT *
  FROM ORGANIZATION_TABLE
  START WITH PARENT_ID       = 6
  CONNECT BY PRIOR   CHILD_ID = PARENT_ID;

此查询带来了 ID 为 6 的父级的所有子级。我的问题是,是否有可能有一个查询既返回 ID 为 6 的父级的子级,又返回同一结果集中的父级。

【问题讨论】:

  • 能否分享一下表结构、当前结果和预期结果?
  • 可能你只需要start with child_id = 6,但是没有样本数据就不好说了。
  • 毕竟这很容易。我正在努力解决许多其他解决方法。是的 START WITH CHILD_ID 成功了。谢谢。

标签: sql database oracle oracle11g


【解决方案1】:

我同意 Boneist - START WITH child_id = 6 可以解决问题 请参阅下面的示例

with ORGANIZATION_TABLE as
(select 1 as parent_id, 0 as child_id from dual union all
 select null as parent_id, 6 as child_id from dual union all
 select 6 as parent_id, 61 as child_id from dual union all
 select 6 as parent_id, 62 as child_id from dual union all
 select 6 as parent_id, 63 as child_id from dual union all
 select 63 as parent_id, 631 as child_id from dual union all
 select 63 as parent_id, 632 as child_id from dual union all
 select 631 as parent_id, 6311 as child_id from dual union all
 select 7 as parent_id, 0 as child_id from dual 
) 
SELECT *
  FROM ORGANIZATION_TABLE
  START WITH child_id       = 6
  CONNECT BY PRIOR   CHILD_ID = PARENT_ID;


1       6
2   6   61
3   6   62
4   6   63
5   63  631
6   631 6311
7   63  632

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多