【问题标题】:How to get the root record in Oracle database如何获取Oracle数据库中的根记录
【发布时间】:2020-04-23 16:02:11
【问题描述】:

从泛型节点(或叶子)开始如何获取根节点?

SELECT 
    ID,MSG_ID,PARENT_ID 
FROM 
    TABLE_X
CONNECT BY PRIOR PARENT_ID = ID;

ID  MSG_ID                              PARENT_ID
4   3                                   NULL
5   93bea0f71b07-4037-9009-f148fa39bb62 4
4   3                                   NULL
6   6f5f5d4ab1ec-4f00-8448-7a6dfa6461b2 4
4   3                                   NULL    
7   3                                   NULL
8   7e0fae569637-4d29-9075-c273eb39ae8e 7
7   3                                   NULL
9   8a3e7485b3e8-45b1-a31d-c52fd32111c0 7
7   3                                   NULL
10  fcc622d5af92-4e61-8d7c-add3da359a8b 7
7   3                                   NULL

如何获取root msg_id?

【问题讨论】:

  • 我读对了吗?有两个根,两者的msg_id 只是'3'?
  • 是的,在数据​​库中我可以有两个根。

标签: sql oracle tree recursive-query hierarchical-query


【解决方案1】:

您走在正确的道路上,但您缺少两个基本要素。

首先,要指明起点,您需要使用start with 子句。显然,它将类似于start with id = <input value>。您没有告诉我们您将如何提供输入值。最常见的方法是使用绑定变量(最好的原因有很多);我在下面的查询中将绑定变量命名为input_id

其次,您只需要“最后”行(因为您正在以相反的方向导航树:朝向根,而不是从根;因此当您以这种方式导航时,根现在是“叶”)。为此,您可以在where 子句中使用connect_by_isleaf 伪列。

因此,查询应如下所示:(请注意,我只选择根消息 ID,因为这就是您所要求的;如果您需要更多列,请将它们包含在 select 中)

select  msg_id
from    table_x
where   connect_by_isleaf = 1  -- keep just the root row (leaf in this traversal)
start   with id = :input_id    -- to give the starting node
connect by prior parent_id = id
;

【讨论】:

    【解决方案2】:

    您可以使用递归查询:

    with cte (id, msg_id, parent_id) as (
        select id, msg_id, parent_id, from mytable where id = ?
        union all
        select t.id, t.msg_id, t.parent_id
        from mytable t
        inner join cte c on c.parent_id = t.id
    )
    select * from cte where parent_id is null
    

    【讨论】:

    • 不需要再次扫描cte - 也不需要lvlwhere 子句应该是 where parent_id is null
    猜你喜欢
    • 2012-04-09
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多