1.首先创建一张表,保存父子关系
drop table tmp_node;
create table tmp_node(id varchar2(500),p_id varchar2(500));
2.向表中插入数据
insert into tmp_node(p_id,id) values(null,1);
insert into tmp_node(p_id,id) values(1,'1-1');
insert into tmp_node(p_id,id) values(1,'1-2');
insert into tmp_node(p_id,id) values('1-1','1-1-1');
insert into tmp_node(p_id,id) values('1-1','1-1-2');
insert into tmp_node(p_id,id) values('1-2','1-2-1');
3.查看表中数据
select * from tmp_node;
编号 | P_ID | ID |
1 |
| 1 |
2 | 1 | 1-1 |
3 | 1 | 1-2 |
4 | 1-1 | 1-1-1 |
5 | 1-1 | 1-1-2 |
6 | 1-2 | 1-2-1 |
4.创建视图(这一步最重要)
create or replace view tmp_node_view as
select distinct level lvl,connect_by_root(id) leaf_id,t.*
from tmp_node t
connect by prior t.p_id = t.id;
5.查看视图数据
select * form tmp_node_view order by leaf_id,lvl;
编号 | LVL | LEAF_ID | ID | P_ID |
1 | 1 | 1 | 1 |
|
2 | 1 | 1-1 | 1-1 | 1 |
3 | 2 | 1-1 | 1 |
|
4 | 1 | 1-1-1 | 1-1-1 | 1-1 |
5 | 2 | 1-1-1 | 1-1 | 1 |
6 | 3 | 1-1-1 | 1 |
|
7 | 1 | 1-1-2 | 1-1-2 | 1-1 |
8 | 2 | 1-1-2 | 1-1 | 1 |
9 | 3 | 1-1-2 | 1 |
|
10 | 1 | 1-2 | 1-2 | 1 |
11 | 2 | 1-2 | 1 |
|
12 | 1 | 1-2-1 | 1-2-1 | 1-2 |
13 | 2 | 1-2-1 | 1-2 | 1 |
14 | 3 | 1-2-1 | 1 |
|
6.使用说明
主要使用的leaf_id和id两个字段的值。
字段说明:lvl字段代表节点的深度,leaf_id代表叶节点。p_id父节点id,id节点本生id。
当需要知道一个节点有哪些父节点的时候,只需要根据leaf_id,查询id字段即可:
select * from tmp_node_view where leaf_id = '1-2-1';
编号 | LVL | LEAF_ID | ID | P_ID |
1 | 1 | 1-2-1 | 1-2-1 | 1-2 |
2 | 3 | 1-2-1 | 1 |
|
3 | 2 | 1-2-1 | 1-2 | 1 |
当需要知道一个节点有哪些子节点的时候,只需要根据id查询leaf_id即可:
select * from tmp_node_view where id = '1-2';
编号 | LVL | LEAF_ID | ID | P_ID |
1 | 1 | 1-2 | 1-2 | 1 |
2 | 2 | 1-2-1 | 1-2 | 1 |
注意:所有的父节点和子节点的查询,都是包含自身节点的。使能在oracle数据库中使用哦.