当前位置:Gxlcms > mysql > Oracle中connectby...startwith...的使用

Oracle中connectby...startwith...的使用

时间:2021-07-01 10:21:17 帮助过:25人阅读

一、语法 大致写法:select * from some_table [where 条件1] connect by [条件2] start with [条件3]; 其中 connect by 与 start with 语句摆放的先后顺序不影响查询的结果,[where 条件1]可以不需要。 [where 条件1]、[条件2]、[条件3]各自作用的范围都不

一、语法
大致写法:select * from some_table [where 条件1] connect by [条件2] start with [条件3];
其中 connect by 与 start with 语句摆放的先后顺序不影响查询的结果,[where 条件1]可以不需要。
[where 条件1]、[条件2]、[条件3]各自作用的范围都不相同:

[where 条件1]是在根据“connect by [条件2] start with [条件3]”选择出来的记录中进行过滤,是针对单条记录的过滤, 不会考虑树的结构;

[条件2]指定构造树的条件,以及对树分支的过滤条件,在这里执行的过滤会把符合条件的记录及其下的所有子节点都过滤掉;

[条件3]限定作为搜索起始点的条件,如果是自上而下的搜索则是限定作为根节点的条件,如果是自下而上的搜索则是限定作为叶子节点的条件;


示例:

create table AA
(
ID NUMBER not null,
PID NUMBER,
XM VARCHAR2(10) not null
);

alter table AA
add constraint PK__AA_ID primary key (ID);

alter table AA
add constraint FK_AA_PID foreign key (PID)
references AA (ID);

表AA中的数据如下:

ID PID XM

1 A
2 1 B1
3 1 B2
4 2 C1
5 2 C2
6 3 C3
7 3 C4

查询获取ID=1的所有子节点记录

select id,xm from aa t connect by prior t.id = t.pid start with t.id=1;

注意:

prior t.id = t.pid 为自父节点开始向下寻找所有子节点;

prior t.pid = t.id 为自本节点开始向上寻找所有父节点;

二、执行原理
tconnect by...sart with...的执行原理可以用以下一段程序的执行以及对存储过程RECURSE()的调用来说明:

/* 遍历表中的每条记录,对比是否满足start with后的条件,如果不满足则继续下一条,
如果满足则以该记录为根节点,然后调用RECURSE()递归寻找该节点下的子节点,
如此循环直到遍历完整个表的所有记录 。*/
for rec in (select * from some_table) loop
if FULLFILLS_START_WITH_CONDITION(rec) then
RECURSE(rec, rec.child);
end if;
end loop;

/* 寻找子节点的存储过程*/
procedure RECURSE (rec in MATCHES_SELECT_STMT, new_parent IN field_type) is
begin
APPEND_RESULT_LIST(rec); /*把记录加入结果集合中*/
/*再次遍历表中的所有记录,对比是否满足connect by后的条件,如果不满足则继续下一条,
如果满足则再以该记录为根节点,然后调用RECURSE()继续递归寻找该节点下的子节点,
如此循环直到找至叶子节点。*/
for rec_recurse in (select * from some_table) loop
if FULLFILLS_CONNECT_BY_CONDITION(rec_recurse.child, new_parent) then
RECURSE(rec_recurse,rec_recurse.child);
end if;
end loop;
end procedure RECURSE;

参考了艾蛋蛋在JavaEye上的发言

http://maruibenze.javaeye.com/blog/208541

人气教程排行