Oracle数据库遍历树形结构表
1、从根结点开始找子节点
/*
create table test (id int ,pid int ,name varchar(10));
insert into test values ( 1, 0 ,'n1' );
insert into test values( 2, 1 ,'n12');
insert into test values( 3, 1 ,'n13');
insert into test values( 4, 2 ,'n21');
insert into test values( 5, 2 ,'n22');
insert into test values( 6, 3 ,'n31');
insert into test values( 7, 3 ,'n32');
insert into test values( 8, 4 ,'n211');
insert into test values( 9, 4 ,'n212');
*/
/*
从根结点开始找子节点(可以指定节点层级)
*/
select id,pid,name ,level from test
--where level =3
start with id =2
connect by prior id = pid;
2、从叶结点开始找根节点
/*create table test (id int ,pid int ,name varchar(10));
insert into test values ( 1, 0 ,'n1' );
insert into test values( 2, 1 ,'n12');
insert into test values( 3, 1 ,'n13');
insert into test values( 4, 2 ,'n21');
insert into test values( 5, 2 ,'n22');
insert into test values( 6, 3 ,'n31');
insert into test values( 7, 3 ,'n32');
insert into test values( 8, 4 ,'n211');
insert into test values( 9, 4 ,'n212');
*/
/*
从叶结点开始找根节点
prior 关键字 与谁放在一起,就是找谁
根节点的父节点不能是他本身,那会造成死循环
*/
select * from test /*where conditions*/
start with id=7
connect by id = prior pid;
今天在群里有个朋友问了
起始地 目的地 距离(公里)
A B 1000
A C 1100
A D 900
A E 400
B D 300
D F 600
E A 400
F G 1000
C B 600
请用SQL语句或一段代码写出从A出发,可达到的目的地(包括间接方式)。
这样的问题
create table dest(
sid char(1),
eid char(1),
distance int);
insert into dest values('A','B',1000);
insert into dest values('A','C',1100);
insert into dest values('A','D',900);
insert into dest values('A','E',400);
insert into dest values('B','D',300);
insert into dest values('D','F',600);
insert into dest values('E','A',400);
insert into dest values('F','G',1000);
insert into dest values('C','B',600);
很自然的就会想到
select sid from dest connect by prior eid=sid start with sid='A';
但是在运行时提示:ORA-01436: 用户数据中的 CONNECT BY 循环
这是a到e,又从e到a,有死循环......
解决方法:
SELECT distinct eid
FROM dest
START WITH SID='A'
connect by nocycle prior eid=sid
原来connect by里还有nocycle