Oracle 中的树层次结构
Tree Hierarchy in Oracle
我刚从 'HackerRank' 那里看到这个问题。
BST
table 包含两列,N
和 P
。 N
代表Node,P
代表Parent:
N P
-- --
1 2
3 2
6 8
9 8
2 5
8 5
5 null
示例输出应为:
1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
我试过的是:
select N,
case
when level = 3 then 'leaf'
when level = 2 then 'inner'
else 'root'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
虽然它给出了正确的结果,但我对代码不满意,因为它硬编码了名称(无论它应该是叶、内部还是根)。当树中有多个层次结构时,此代码也会失败。
有人可以建议任何其他编写相同代码的优雅方式,以便它不会在多个层次结构中失败吗?
您可以利用 connect_by_isleaf
pseudocolumn,并且根始终具有级别 1 的事实:
select n,
case
when connect_by_isleaf = 1 then 'leaf'
when level = 1 then 'root'
else 'inner'
end
from bst
start with p is null
connect by p = prior n
order by n;
Oracle 提供 a pseudocolumn CONNECT_BY_ISLEAF
to test 多叶性。 root 的测试与 START WITH 子句相同。其他任何东西都是内在的。所以你应该这样做
select N ,
case
when CONNECT_BY_ISLEAF = 1 then 'leaf'
WHEN P is NULL then 'root'
else 'inner'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
请用户像下面一样(对于 MS SQL 层次结构)
;具有层次结构(ChildId、Generation、ParentId)
作为
(
SELECT Id, 0 AS代, ParentId
FROM Table_Name 作为第一代
其中 ParentId 为 NULL
联合所有
SELECT NextGeneration.Id, Parent.Generation + 1, Parent.ChildId
FROM Table_Name 作为下一代
INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentId = Parent.ChildId
)
SELECT *FROM Hierarchy ORDER BY Generation;
我刚从 'HackerRank' 那里看到这个问题。
BST
table 包含两列,N
和 P
。 N
代表Node,P
代表Parent:
N P
-- --
1 2
3 2
6 8
9 8
2 5
8 5
5 null
示例输出应为:
1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
我试过的是:
select N,
case
when level = 3 then 'leaf'
when level = 2 then 'inner'
else 'root'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
虽然它给出了正确的结果,但我对代码不满意,因为它硬编码了名称(无论它应该是叶、内部还是根)。当树中有多个层次结构时,此代码也会失败。
有人可以建议任何其他编写相同代码的优雅方式,以便它不会在多个层次结构中失败吗?
您可以利用 connect_by_isleaf
pseudocolumn,并且根始终具有级别 1 的事实:
select n,
case
when connect_by_isleaf = 1 then 'leaf'
when level = 1 then 'root'
else 'inner'
end
from bst
start with p is null
connect by p = prior n
order by n;
Oracle 提供 a pseudocolumn CONNECT_BY_ISLEAF
to test 多叶性。 root 的测试与 START WITH 子句相同。其他任何东西都是内在的。所以你应该这样做
select N ,
case
when CONNECT_BY_ISLEAF = 1 then 'leaf'
WHEN P is NULL then 'root'
else 'inner'
end
from BST
start with P is NULL
connect by P = prior N
order by N;
请用户像下面一样(对于 MS SQL 层次结构)
;具有层次结构(ChildId、Generation、ParentId)
作为
(
SELECT Id, 0 AS代, ParentId
FROM Table_Name 作为第一代
其中 ParentId 为 NULL
联合所有
SELECT NextGeneration.Id, Parent.Generation + 1, Parent.ChildId
FROM Table_Name 作为下一代
INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentId = Parent.ChildId
)
SELECT *FROM Hierarchy ORDER BY Generation;