connect-by-prior-start-with-实现递归查询

有一个组织表 org, 子组织的 parent_id = 父组织的 id
想实现递归查找某个组织下的所有自组织

背景

表数据如下
|--090201 (根节点)
|--|--0902010001 (无子节点了)
|--|--0902010002 (有两个子节点)
|--|--|---0902010002001 (末级节点)
|--|--|---0902010002002 (末级节点)

递归查找某组织下所有组织不包括自身

select o.id from org o
    connect by prior o.id = o.parent_id
    start with o.parent_id='090201'

显示结果
0902010001
0902010002
0902010002001
0902010002002

递归查找某组织下所有组织包括自身

select o.id from org o
    connect by prior o.id = o.parent_id
    start with o.id='090201'

显示结果 注意 此时查找的本身组织id也会在里面
090201
0902010001
0902010002
0902010002001
0902010002002

递归查找某组织下所有末级组织

select * from org o
    where 1=1
    and o.id in     
    --此处需要用id,若传进来的是末级节点,则sql返回其本身,否则返回其递归子组织的末级节点
    --如果是parent_id,若传进来是末级节点,则sql返回空,否则返回其递归子组织的末级节点
        (select o1.id from org o1
            connect by prior o1.id = o1.parent_id
            start with o1.id='0902' )
    and not EXISTS
        (select o2.* from org o2
            where o2.parent_id = o.id)

显示结果(传入参数是 0902)
0902010002001
0902010002002

显示结果(传入参数是 0902010001)
0902010001