【发布时间】:2022-01-15 21:55:09
【问题描述】:
我有一张带有父/子 ID 的表格,我正在尝试获取给定 ID 的所有级别的父子和子节点的完整列表。
基本上,对于给定的 id,从层次结构一直向下一直向上。
我试过 connect by,但也许递归 CTE 会更好?
select 'abc' as child, null as parent from dual union all
select 'mno' as child, 'abc' as parent from dual union all
select 'def' as child, 'abc' as parent from dual union all
select '123' as child, 'abc' as parent from dual union all
select 'qrs' as child, '123' as parent from dual union all
select '789' as child, 'def' as parent from dual union all
select 'xyz' as child, '123' as parent from dual
例如:
| Child | Parent |
|---|---|
| abc | null |
| mno | abc |
| def | abc |
| 123 | abc |
| qrs | 123 |
| 789 | def |
| xyz | 123 |
对于 123,所需的输出:
- xyz > 123 > abc
- qrs > 123 > abc
对于 abc,所需的输出:
- xyz > 123 > abc
- 789 > def > abc
- qrs > 123 > abc
- mno > abc
这是我的尝试。 full_hier 是子路径和父路径的串联 + 子字符串,这似乎有点 hacky。另外,我得到了一些我不确定如何过滤掉的额外结果(例如:def > abc 被返回,但我不想要它,因为它是在 789 > def > abc 中捕获的)。
select
connect_by_root child,
substr(sys_connect_by_path(child, '>' ),2) as child_hier
, substr(sys_connect_by_path(parent, '>' ),2) as parent_hier
, case
when parent is null then substr(sys_connect_by_path(child, '>' ),2)
else substr(sys_connect_by_path(child, '>' ),2) || substr(substr(sys_connect_by_path(parent, '>' ),2), instr(substr(sys_connect_by_path(parent, '>' ),2),'>',1,1))
end as full_hier
, level
from
(
select 'abc' as child, null as parent from dual union all
select 'mno' as child, 'abc' as parent from dual union all
select 'def' as child, 'abc' as parent from dual union all
select '123' as child, 'abc' as parent from dual union all
select 'qrs' as child, '123' as parent from dual union all
select '789' as child, 'def' as parent from dual union all
select 'xyz' as child, '123' as parent from dual
) table_name
where 1=1
--and connect_by_isleaf = 1
--and connect_by_root child in ('123')
and child = 'abc'
connect by child = prior parent
--connect_by prior parent = child
感谢观看,不胜感激!
【问题讨论】:
-
“孩子”是指“严格”的孩子(不包括给定的 id 本身作为它自己的孩子)?那么它不是真正的“在所有级别”,而是“在级别 > 1” - 给定的 id 是它自己的子级 = 0。然后,如果给定的 id 是叶子(没有严格的子级),则查询将不返回任何内容(没有行)?
-
哦 - 实际上您也不想为不是叶子的孩子显示一行。似乎您只想显示给定 id 的叶子后代的路径,它们不等于给定的 id。 (换句话说,如果给定的 id 已经是叶子,则不返回任何行)。是这样吗?
标签: sql oracle oracle11g hierarchical-data