我有一个结构(例如,括号(id,parent_id)):
在输入中我有id列表 如果我没有id父目录,但我有子id,那么我必须显示所有祖先: 例如: 输入:83,46,43,48 输出:
我发明了请求:
SELECT *
FROM (SELECT distinct *
FROM Table a
START WITH N in (83, 46, 43, 48) CONNECT BY PRIOR N_PARENT = N) a
START WITH N_PARENT in 0 CONNECT BY PRIOR N = N_PARENT
ORDER SIBLINGS BY N
但是在大数据方面却很慢。我可以使用一个CONNECT BY
提出请求吗?
答案 0 :(得分:2)
with tree as (
SELECT t.name, t.id, t.parent, LEVEL lvl, connect_by_root(id) root
FROM t
CONNECT BY PRIOR parent = id
START WITH id IN (83, 98, 46, 43, 48)
), ordered_tree as (
select name,
id,
parent,
row_number() over (partition by id order by id) rn
from tree
order by root, lvl desc
)
select name, id, parent
from ordered_tree where rn = 1