如何获取Oracle数据库中的根记录

How to get the root record in Oracle database

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

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

如何获取根msg_id?

您可以使用递归查询:

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

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

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

其次,您只需要 "last" 行(因为您在相反的方向导航树:朝向根,而不是从根开始;所以根现在是 "leaf" 作为您以这种方式导航)。为此,您可以在 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
;