简体   繁体   English

通过子句连接以获取层次结构的顶部

[英]Connect by clause to get the top of hierarchy

I am facing an issue while using the CONNECT BY clause in Oracle for finding hierarchical data. 在Oracle中使用CONNECT BY子句查找分层数据时,我遇到了一个问题。 Let me give an example: A is my parent part which has child part B and B also has a child part C. When I am using the CONNECT BY clause I am able to get all the three levels but I only want the top most level, ie A. 让我举个例子:A是我的父部件,它有B子部件,而B也有C子部件。当我使用CONNECT BY子句时,我能够获得所有三个级别,但我只想要最高级,即A。

Oracle has a LEVEL pseudocolumn that you can use: Oracle有一个LEVEL伪列 ,您可以使用:

SELECT
  myTable.ID,
  myTable.ParentID
FROM myTable
WHERE LEVEL = 1
CONNECT BY PRIOR myTable.ID = myTable.ParentID

To find a top-level (root) value from any level, precede the column name with the CONNECT_BY_ROOT operator: 要从任何级别查找顶级(根)值,请在列名之前加上CONNECT_BY_ROOT运算符:

SELECT
  myTable.ID,
  myTable.ParentID,
  CONNECT_BY_ROOT myTable.ID AS "Top Level ID"
FROM myTable
CONNECT BY PRIOR myTable.ID = myTable.ParentID

I am adding this solution for tables with one or multiple trees (hierarchical data). 我正在为具有一棵或多棵树的表(分层数据)添加此解决方案。

Starting with one node (row) somewhere in the tree (hierarchical data), wanting to find the top node (root). 从树中某处的一个节点(行)(分层数据)开始,想要找到顶部节点(根)。

The query is taking advantage of the fact that the ONLY the top node (root) of a tree don't have a parent, which is a very common attribute of the top node (root) in any tree structure. 查询花费的事实, 唯一的一棵树的顶部节点(根)没有父母,这是在任何树状结构的顶层节点(根)的一个非常普遍的属性优势。

SELECT
  c.id
FROM 
  node c
WHERE
  c.parent_id is null
CONNECT BY PRIOR
  c.parent_id = c.id
START WITH
  c.id = 1059002615
SELECT * FROM (
  SELECT CONNECT_BY_ROOT myTable.ID AS "Top Level ID"
  FROM myTable
  CONNECT BY PRIOR myTable.ID = myTable.ParentID
)
WHERE myTable.ParentID IS NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM