Oracle 分层查询仅 select 根父级

Oracle hierachial query to select only the root parents

我有一个树数据,我正在尝试 select 只有根父级。数据可能是更大集合的子集,因此 parent 可能不为空。我想要数据集中每棵树的最顶层。

 with test_data as (
 select '1' ID,'100' name, null parent  from dual
 union
 select '2' ID,'200' name, null parent  from dual
 union
 select '3' ID,'300' name, null parent  from dual
 union
 select '1.1' ID,'1.100' name, '1' parent  from dual
 union
 select '2.1' ID,'2.100' name, '2' parent  from dual
 union
 select '3.1' ID,'3.100' name, '3' parent  from dual
 union
 select '3.1.1' ID,'3.1.100' name, '3.1' parent  from dual
 union
 select '3.1.2' ID,'3.1.2.100' name, '3.1' parent  from dual
 union
 select '4.1' ID,'4.100' name, '4' parent  from dual
 union
 select '4.1.1' ID,'4.1.100' name, '4.1' parent  from dual
 union
 select '4.1.2' ID,'4.1.2.100' name, '4.1' parent  from dual )
 select * from test_data
 start with parent is null
 connect by parent=prior id

我希望看到的结果是

     ID    NAME      PAR
    ----- --------- ---
    1     100
    2     200
    3     300
    4.1   4.100      4

Rowid 4 未被 select 编辑,因为子集的一部分是父代,但由于 4.1 是该数据集中的最顶层,我想 return 该行。所以基本上,我想查看每个层次结构的所有最高级别记录。

谢谢。

一种方法是使用 not exists:

select id, name, parent
from test_data td
where not exists (select 1
                  from test_data td2
                  where td.parent = td2.id
                 );