oracle的start with connect by prior如何使用
oracle的start with connect by prior是根据条件递归查询"树",分为四种使用情况:
第一种:start with 子节点ID=‘…’ connect by prior 子节点ID = 父节点ID
查询结果是:自己所有的后代节点(包括自己)。
例如:
select OFFICE_CODE,PARENT_CODE,OFFICE_NAME from js_sys_office o start
with o.office_code=‘100199’ connect by prior
o.office_code=o.parent_code
按照条件office_code=‘100199’,对’100199’(包括自己)及其子节点进行递归查询。
第二种:start with 子节点ID=‘…’ connect by 子节点ID = prior 父节点ID
查询结果是:自己所有的前代节点(包括自己)
例如:
select OFFICE_CODE,PARENT_CODE,OFFICE_NAME from js_sys_office o start
with o.office_code=‘100199’ connect by o.office_code = prior
o.parent_code
按照条件office_code=‘100199’,对’100199’(包括自己)及其父节点进行递归查询。
第三种:start with 父节点ID=‘…’ connect by prior 子节点ID = 父节点ID
查询结果是:自己所有的后代节点(不包括自己)。
例如:
select OFFICE_CODE,PARENT_CODE from js_sys_office o start with
o.parent_code=‘100199’ connect by prior o.office_code=o.parent_code
按照条件parent_code=‘100199’,对’100199’(不包括自己)子节点进行递归查询。
第四种:start with 父节点ID=‘…’ connect by 子节点ID = prior 父节点ID
查询结果是:自己的第一代后节点和所有的前代节点(包括自己)。
例如:
select OFFICE_CODE,PARENT_CODE from js_sys_office o start with
o.parent_code=‘100199’ connect by o.office_code = prior o.parent_code
按照条件parent_code=‘100199’,对’100199’(包括自己)的第一代孩子们及其父节点进行递归查询。
如果有where 条件,如下
select OFFICE_CODE,PARENT_CODE from js_sys_office o where 条件 start
with o.parent_code=‘100199’ connect by prior
o.office_code=o.parent_code
执行顺序为先执行start with connect by prior,然后再按照where条件进行过滤。