oracle递归寻找父节点

/ 技术 / 1640浏览
准备数据
创建表
create table MEUM_TEST
(
  cid         NUMBER,
  cname       VARCHAR2(32),
  parent_id   NUMBER,
  create_time DATE,
  org_level   NUMBER
);
-- Add comments to the table 
comment on table MEUM_TEST
  is '机构组织简化表';
-- Add comments to the columns 
comment on column MEUM_TEST.cid
  is '主键ID';
comment on column MEUM_TEST.cname
  is '组织名称';
comment on column MEUM_TEST.parent_id
  is '上级组织ID';
comment on column MEUM_TEST.create_time
  is '创建时间';
comment on column MEUM_TEST.org_level
  is '组织级别';
插入表数据
输出层级关系(从上往下)
select sys_connect_by_path(cname,'->'),cname ,org_level
from MEUM_TEST t
--where t.org_level=4
start with parent_id=0
connect by prior t.cid=t.parent_id;

image-20200625162913136

查找单个节点的根(从下往上)
select sys_connect_by_path(cname,'->'),cname ,org_level
from MEUM_TEST t
--where t.org_level=4
start with cname='杭州市'
connect by  t.cid= prior t.parent_id;

image-20200625163232591

prior和start with关键字是可选项:

prior运算符必须放置在连接关系的两列中某一个的前面。对于节点间的父子关系,prior运算符在一侧表示父节点,在另一侧表示子节点,从而确定查找树结构是的顺序是自顶向下还是自底向上。在连接关系中,除了可以使用列名外,还允许使用列表达式。
start with子句为可选项,用来标识哪个节点作为查找树型结构的根节点。若该子句被省略,则表示所有满足查询条件的行作为根节点。