connect by prior id= pid start with id='1' 树结构查询

基础表创建:

with temp as (
select '公司' name, '1' id, '' pid from dual union all
select '部门1'  name , '11' id, '1' pid from dual union all
select '部门2'  name , '12' id, '1' pid from dual union all
select '员工11' name , '111' id , '11' pid from dual union all
select '员工12' name , '112' id , '11' pid from dual union all
select '员工21' name , '121' id , '12' pid from dual 
)

等号左边的字段为基础,查询右边字段=左边字段的

level可以查看距离父节点的距离

从上往下查

通过根节点可以获取包括该根节点及以下的所有子节点
select temp.*,level from temp
connect by prior id= pid
start with id='1'

 

根节点可以多选
select * from temp
connect by prior  id= pid
start with id in ('11' ,'12')

添加where语句

select * from temp
where id = '111'
connect by prior  id= pid
start with id in ('11' ,'12')

 从下往上查

select * from temp
connect by prior pid= id 
start with id = '121'

原文地址:https://www.cnblogs.com/-beauTiFul/p/9121553.html