将以递归方式生成child_id的SQL查询

时间:2012-06-20 13:40:02

标签: sql oracle recursive-query

我有以下表结构:

ORGANIZATION_ID   | Name  |  PARENT_ID
--------------------------------------------------
1                 | A     |     0   -Indicates root
2                 | B     |     1
3                 | C     |     2
4                 | D     |     2
5                 | E     |     4
6                 | F     |     1
7                 | G     |     1
8                 | H     |     7
9                 | J     |     8
10                | K     |     9

我在撰写Oracle SQL查询时并不是那么出色。如果我传入某个组织ID,如何生成所有(*)子组织的列表?

例如,如果我传入2,从逻辑上讲,我会查找父ID为2的所有行,然后我会递归查看每一行做同样的事情。

我知道逻辑,如何在oracle中使用sql查询重新创建它?

2 个答案:

答案 0 :(得分:3)

CONNECT BY可用于进行此递归查询:

SELECT organization_id, name
FROM t
CONNECT BY PRIOR organization_id = parent_id
START WITH organization_id = 2

答案 1 :(得分:2)

如果使用Oracle 11g,Oracle递归子查询可以替代。

with orgs (organization_id, name, parent_id) as (
    select organization_id, name, parent_id 
        from organization
        where organization_id=2
    union all
        select organization_id, name, parent_id 
        from organization org join orgs on org.parent_id=orgs.organization_id)
search depth first by organization_id set a
select organization_id, name
from orgs;