【转】oracle中的递归查询
遇到的需求是查看我们给用户建立的站点的栏目被调整了N多次后现在是什么样子了,于是在网上找到相关的资料,用oracle特有的语句查询。
详细内容转自http://www.javaeye.com/topic/287749
Start with...Connect By子句递归查询一般用于一个表维护树形结构的应用。
创建示例表:
CREATE TABLE TBL_TEST
(
ID NUMBER,
NAME VARCHAR2(100 BYTE),
PID NUMBER DEFAULT 0
);
(
ID NUMBER,
NAME VARCHAR2(100 BYTE),
PID NUMBER DEFAULT 0
);
插入测试数据:
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('1','10','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('2','11','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('3','20','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('4','12','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('5','121','2');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('2','11','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('3','20','0');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('4','12','1');
INSERT INTO TBL_TEST(ID,NAME,PID) VALUES('5','121','2');
从Root往树末梢递归
select * from TBL_TEST
start with id=1
connect by prior id = pid
start with id=1
connect by prior id = pid
从末梢往树ROOT递归
select * from TBL_TEST
start with id=5
connect by prior pid = id
start with id=5
connect by prior pid = id
=====
对于oracle进行简单树查询(递归查询)
DEPTID | PAREDEPTID | NAME |
NUMBER | NUMBER | CHAR (40 Byte) |
部门id | 父部门id(所属部门id) | 部门名称 |
通过子节点向根节点追朔.
- select * from persons.dept start with deptid=76 connect by prior paredeptid=deptid
- select * from persons.dept start with deptid=76 connect by prior paredeptid=deptid
通过根节点遍历子节点.
- select * from persons.dept start with paredeptid=0 connect by prior deptid=paredeptid
- select * from persons.dept start with paredeptid=0 connect by prior deptid=paredeptid
可通过level 关键字查询所在层次.
- select a.*,level from persons.dept a start with paredeptid=0 connect by prior deptid=paredeptid
- select a.*,level from persons.dept a start with paredeptid=0 connect by prior deptid=paredeptid
再次复习一下:start with ...connect by 的用法, start with 后面所跟的就是就是递归的种子。
递归的种子也就是递归开始的地方 connect by 后面的"prior" 如果缺省:则只能查询到符合条件的起始行,并不进行递归查询;
connect by prior 后面所放的字段是有关系的,它指明了查询的方向。
其他参考:
http://zhaolinjnu.blog.163.com/blog/static/2280005200841621159121/
http://www.javaeye.com/topic/287749
http://www.javaeye.com/wiki/topic/746687
posted on 2011-02-17 15:34 littlebamboo 阅读(194) 评论(0) 编辑 收藏 举报