Oracle中的树层次结构

时间:2017-06-05 06:02:11

标签: sql oracle hierarchical-data recursive-query

我刚刚从HackerRank'中发现了这个问题。 BST表包含两列NPN代表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;

虽然它给出了正确的结果,但我对代码不满意,因为它硬编码了名称(无论是叶子,内部还是根)。当树中有多个层次结构时,此代码也将失败。

有人可以建议任何其他优雅的方式来编写相同的代码,以便它不会因多层次结构而失败吗?

3 个答案:

答案 0 :(得分:4)

您可以使用http://beta.beantin.se/clearing-linkedin-link-sharing-preview-cache/,以及根始终具有级别1的事实:

Original link: http://beantin.se/consultant-resume 
"New" link: http://beantin.se/consultant-resume?1

答案 1 :(得分:3)

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;

答案 2 :(得分:0)

请用户如下(适用于MS SQL层次结构)

; WITH Hierarchy(ChildId,Gen​​eration,ParentId)    如    (        SELECT Id,0 AS Generation,ParentId               FROM Table_Name AS FirtGeneration               在哪里ParentId为NULL
       UNION ALL         SELECT NextGeneration.Id,Parent.Generation + 1,Parent.ChildId               FROM Table_Name AS NextGeneration               INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentId = Parent.ChildId
   )

SELECT * FROM Hierarchy ORDER BY Generation;