从通用节点(或叶子)开始如何获得根节点?
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?
你走在正确的道路上,但你缺少两个基本要素。
首先,为了表示起点,你需要使用 start with
条款。很明显,它会是这样的 start with id = <input value>
. 你没有告诉我们你将如何提供输入值。最常见的方法是使用绑定变量(出于许多原因,这是最好的);我将绑定变量命名为 input_id
在下面的查询中。
第二,你只想要 "最后 "一行(因为你是以相反的方向导航树:朝向根部,而不是从根部开始;所以当你以这种方式导航时,根部现在是 "叶子")。为此,你可以使用 connect_by_isleaf
中的伪列。where
子句。
所以,查询应该是这样的:(注意,我只选择了根消息的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
;
你可以使用递归查询。
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