现实中我们经常需要用到一些递归查询,下面我们来介绍下ORACLE中递归查询的使用。

首先我们先新建一个表来存储以上信息

create table FAMILY
(
  person_id INTEGER,
  name      VARCHAR2(10),
  parent_id INTEGER
)

插入测试数据

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (1, 'Apple', 2);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (2, 'Zoe', 4);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (3, 'Tom', 4);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (4, 'John', 7);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (5, 'Peter', 6);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (6, 'Robert', 10);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (7, 'Mary', null);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (8, 'Jenny', 7);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (9, 'Sam', 10);

insert into FAMILY (PERSON_ID, NAME, PARENT_ID) values (10, 'Li Lei', null);

在Oracle中使用start with connect by prior字句实现递归查询

select t.*, level
  from family t
 start with t.person_id = 1
connect by t.person_id = prior t.parent_id;--找寻person_id=1的人的祖先

得到,如图我们可以得到Apple的父亲是Zoe,Zoe父亲是John,看level依次类推,Mary是他们老祖宗,

当然,我们除了可以得到某个节点的父节点,

select t.*, level
  from family t
 start with t.person_id = 4
connect by t.person_id = prior t.parent_id;--找寻person_id=4的人的祖先

也可以得到某个节点的子节点:

select t.*, level
  from family t
 start with t.person_id = 4
connect by prior t.person_id =  t.parent_id;--找寻person_id=4的人的传人

得到,其中Tom跟Zoe都是John的子节点。

下一篇介绍DB2中的递归查询

posted on 2016-01-18 16:26  回家的流浪者  阅读(404)  评论(0编辑  收藏  举报