既然会看ORACLE递归查询那么大家应该是比较清楚递归是什么意思了,在这里我就不多加说明了,只作简单介绍了。
言归正传所谓递归查询那么数据表中数据的结构应该是符合递归查询的基本条件,即表中有ID,PID(节点编号、父节点编号)如果把数据以UI的方式展现出来应该是一棵或多棵树了。
那么我们要以其中一个节点去递归查询出这个节点子节点或父节点的过程就是我们所要说明的。
递归查询语法:
select ... from tablename where 条件4 start with 条件1 connect by 条件2 AND 条件3
如下面的表结构http://www.cnblogs.com/wanghonghu/archive/2012/08/31/2665945.html
CREATE TABLE SC_DISTRICT ( IID NUMBER(10) NOT NULL, PARENT_ID NUMBER(10), INAME VARCHAR2(255 BYTE) NOT NULL, BZ NUMBER(4)
); ALTER TABLE SC_DISTRICT ADD ( CONSTRAINT SC_DISTRICT_PK PRIMARY KEY (IID)); ALTER TABLE SC_DISTRICT ADD ( CONSTRAINT SC_DISTRICT_R01 FOREIGN KEY (PARENT_ID) REFERENCES SC_DISTRICT (IID));
INSERT INTO SC_DISTRICT(IID,INAME) VALUES(1,'四川省'); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(2,1,'巴中市',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(3,1,'达州市',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(4,2,'巴州区',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(5,2,'通江县',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(6,2,'平昌县',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(7,3,'通川区',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(8,3,'宣汉县',0); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(9,8,'塔河乡',1); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(10,8,'三河乡',1); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(11,8,'胡家镇',1); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(12,8,'南坝镇',1); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(13,6,'大寨乡',2); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(14,6,'响滩镇',2); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(15,6,'龙岗镇',2); INSERT INTO SC_DISTRICT(IID,PARENT_ID,INAME,BZ) VALUES(16,6,'白衣镇',2);
如果如图
--查询平昌县的子节点
SELECT * FROM SC_DISTRICT
START WITH INAME = '平昌县'
CONNECT BY PRIOR IID = PARENT_ID
--查询平昌县的父节点
SELECT * FROM SC_DISTRICT
START WITH INAME = '平昌县'
CONNECT BY PRIOR PARENT_ID= IID
--只是查询当前节点BZ为0的,但不会查询节点BZ为0的子节点(这点大家注意了)
SELECT * FROM SC_DISTRICT
START WITH INAME = '平昌县' AND BZ = 0
CONNECT BY PRIOR PARENT_ID= IID ;
--查询当前节点和子节点的BZ为0的方法
SELECT * FROM SC_DISTRICT WHERE BZ = 0
START WITH INAME = '平昌县'
CONNECT BY PRIOR PARENT_ID= IID
--此方式不仅可以查询BZ为0的节点而且会不再去遍历此节点的子节点
SELECT * FROM SC_DISTRICT START WITH INAME = '平昌县'
CONNECT BY PRIOR PARENT_ID= IID AND BZ = 0
如果大家对递归的方式比较了解的话上面的几种方式就很容易理解了。