查找Oracle 10g中任何父节点的所有子节点

时间:2015-03-05 17:34:56

标签: oracle plsql oracle10g plsqldeveloper

我的表结构是:

COMPANY_ID, ID, PARENT_ID

以下是该表的一部分:

     | COMPANY_ID |     ID      |  PARENT_DID |
     |------------|-------------|-------------|
     | 12         |      1      |    null     |
     | 12         |      3      |     1       |
     | 12         |      2      |     1       |
     | 12         |      4      |     3       |
     | 12         |      7      |     4       |
     | 14         |      3      |     null    |

我想查找Oracle 10g中任何ID的所有子孙ID。对于COMPANY_ID = 12和ID = 3,结果必须如此:

  

3,4,7

我试过这个,但这不起作用:

SELECT id
FROM TABLE_NAME
  START WITH ID        = 3
  CONNECT BY PARENT_ID = PRIOR ID
AND COMPANY_ID=12;

1 个答案:

答案 0 :(得分:4)

您需要将其限制为与另一个PRIOR子句相同的公司ID,并将您要查找的特定公司ID移入START WITH子句:

SELECT id
FROM TABLE_NAME
START WITH ID = 3 AND COMPANY_ID = 12
CONNECT BY PARENT_ID = PRIOR ID AND COMPANY_ID = PRIOR COMPANY_ID;

        ID
----------
         3 
         4 
         7 

如果您指定了多个起始ID(正如您在评论中提到的那样),您可能会获得重复项,您可以使用DISTINCT来抑制这些重复项;但是如果你想看看哪些后代与你的起始ID相关联,那么有一个方便的connect_by_root operator可以让你跟踪它;例如:

SELECT CONNECT_BY_ROOT id AS root_id, id AS id
FROM TABLE_NAME
START WITH ID IN (3, 7)
AND COMPANY_ID = 12
CONNECT BY PARENT_ID = PRIOR ID and COMPANY_ID = PRIOR COMPANY_ID;

   ROOT_ID         ID
---------- ----------
         3          3 
         3          4 
         3          7 
         7          7