达梦树形递归查询

时间:2024-04-12 20:44:49

假设有树形表,表结构和数据如下:
CREATE TABLE tree(id int, name varchar(10), pid int);

insert into tree values(0,‘中国’,null);
insert into tree values(1,‘四川’,0);
insert into tree values(2,‘贵州’,0);
insert into tree values(3,‘云南’,0);
insert into tree values(4,‘重庆’,0);
insert into tree values(5,‘*’,0);
insert into tree values(6,‘成都’,1);
insert into tree values(7,‘绵阳’,1);
insert into tree values(8,‘泸州’,1);
insert into tree values(9,‘宜宾’,1);
insert into tree values(10,‘武侯’,6);
insert into tree values(11,‘青羊’,6);
insert into tree values(12,‘双流’,6);
insert into tree values(13,‘华阳’,12);
insert into tree values(14,‘中和’,12);
insert into tree values(15,‘安县’,7);
insert into tree values(16,‘北川’,7);
-要求:
–1、往上查:查询节点“华阳”的所有父节点,得到结果如下
id name pid


13 华阳 12
12 双流 6
6 成都 1
1 四川 0
0 中国 null

–2、往下查:查询节点“四川”的所有子节点,得到结果如下
id name pid


1 四川 0
6 成都 1
7 绵阳 1
8 泸州 1
9 宜宾 1
10 武侯 6
11 青羊 6
12 双流 6
13 华阳 12
14 中和 12
15 安县 7
16 北川 7

查询语句:
1、SELECT * FROM Tree START WITH Id = 13 CONNECT BY ID = PRIOR PId;
达梦树形递归查询
2、SELECT * FROM Tree START WITH Id = 1 CONNECT BY PRIOR ID = PId;
达梦树形递归查询