connect by 用法

1。项目中遇到了父子层级关系的问题,刚开始的处理办法是:先将数据从数据库中查处理,然后再在代码中遍历,这样做,代码写的比较臃肿,再加上还有其他的业务要处理,比较麻烦,后来就查找了一些资料,发现oracle中有个函数connect by可以解决这个问题,写起来,代码也比较简洁
这个就写个例子来说明一下这个问题:
1首先创建一张表

create table text_cen (
       id  varchar2(20),
       name varchar2(20),
       parentid varchar2(20)
);
insert into text_cen(id,name,parentid) values ('001','root',null);
insert into text_cen(id,name,parentid) values ('001001','大禹','001');


insert into text_cen(id,name,parentid) values ('001002','龙心','001');
insert into text_cen(id,name,parentid) values ('001003','五毒圣君','001');
insert into text_cen(id,name,parentid) values ('001001001','分页','001001');
insert into text_cen(id,name,parentid) values ('001001002','递归','001001');
insert into text_cen(id,name,parentid) values ('001001003','排序','001001');
insert into text_cen(id,name,parentid) values ('001001003001','计数','001001003');
insert into text_cen(id,name,parentid) values ('001002001','张无忌','001002');
insert into text_cen(id,name,parentid) values ('001002002','周杰','001002');
insert into text_cen(id,name,parentid) values ('001003001','林心如','001003');

然后查看一下表中的数据
在这里插入图片描述
现在查找一下id为001001的子孙后代

select * from text_cen 
start with id = '001001'
connect by prior id = parentid

这个还有一些属性

level:标记层级级数,最上层节点为1,之后为2、3……。

CONNECT_BY_ISCYCLE:标记此节点是否为某一个祖先节点的父节点,导致循环,1为是,0为否。

CONNECT_BY_ISLEAF :标记此节点是否为叶子节点,即没有子节点,1为是,0为否。

CONNECT_BY_ROOT:标记此节点的祖先节点,后面加列名或表达式,取祖先节点的记录值。

sys_connect_by_path(id,’-’)和level用法


select id,name,level,sys_conect_by_path(name,'-')
from employee
start with name="小明"
connect by prior id=manager_id 

在这里插入图片描述

Guess you like

Origin blog.csdn.net/jtpython666/article/details/119173318