一文解析ORACLE树结构查询
我们在日常程序设计中,经常会遇到树状结构的表示,例如组织机构、行政区划等等。这些在数据库中往往通过一张表进行展示。这里我们以一张简单的行政区划表为例进行展示,在实际使用过程中,可以为其添加其他描述字段以及层级。
表中通过ID和PID关联,实现树状结构的存储。建表以及数据语句如下:
— Create table
create table TREETEST
(
id NVARCHAR2(50),
pid NVARCHAR2(50),
name NVARCHAR2(50)
)
create table TREETEST
(
id NVARCHAR2(50),
pid NVARCHAR2(50),
name NVARCHAR2(50)
)
insert into TREETEST (ID, PID, NAME) values (‘1’, null, ‘山东省’);
insert into TREETEST (ID, PID, NAME) values (‘2’, ‘1’, ‘青岛市’);
insert into TREETEST (ID, PID, NAME) values (‘3’, ‘1’, ‘烟台市’);
insert into TREETEST (ID, PID, NAME) values (‘4’, null, ‘河南省’);
insert into TREETEST (ID, PID, NAME) values (‘5’, null, ‘河北省’);
insert into TREETEST (ID, PID, NAME) values (‘6’, ‘2’, ‘市南区’);
insert into TREETEST (ID, PID, NAME) values (‘7’, ‘2’, ‘市北区’);
insert into TREETEST (ID, PID, NAME) values (‘8’, ‘2’, ‘即墨市’);
insert into TREETEST (ID, PID, NAME) values (‘2’, ‘1’, ‘青岛市’);
insert into TREETEST (ID, PID, NAME) values (‘3’, ‘1’, ‘烟台市’);
insert into TREETEST (ID, PID, NAME) values (‘4’, null, ‘河南省’);
insert into TREETEST (ID, PID, NAME) values (‘5’, null, ‘河北省’);
insert into TREETEST (ID, PID, NAME) values (‘6’, ‘2’, ‘市南区’);
insert into TREETEST (ID, PID, NAME) values (‘7’, ‘2’, ‘市北区’);
insert into TREETEST (ID, PID, NAME) values (‘8’, ‘2’, ‘即墨市’);
那对于树状结构如何查询呢?Oracle提供递归查询的方式进行查询,基本语法如下:
SELECT [Column]…..
FEOM [Table]
WHERE Conditional1
START WITH Conditional2
CONNECT BY PRIOR Conditional3
ORDER BY [Column]
FEOM [Table]
WHERE Conditional1
START WITH Conditional2
CONNECT BY PRIOR Conditional3
ORDER BY [Column]
说明:
- 条件1—过滤条件,对全部返回的记录进行过滤。
- 条件2—根节点的限定条件,固然也可以放宽权限得到多个根节点,也就是获取多个树
- 条件3—链接条件,目的就是给出父子之间的关系是什么,根据这个关系进行递归查询(在上述表中就是ID=PID)
- 排序—对全部返回记录进行排序
下面我们结合具体实例来看:
1、查询山东省下面的所有子节点
SELECT *
FROM TREETEST t
START WITH t.PID=1
CONNECT BY PRIOR t.ID = t.PID
FROM TREETEST t
START WITH t.PID=1
CONNECT BY PRIOR t.ID = t.PID
其中ID为1的为山东省节点,查询结果如下:
2、查询青岛市的下一级子节点(注意和上面区分,全部子节点和下一级子节点)
3、如果需要获取将山东省青岛市等连接起来显示,可以使用SYS_CONNECT_BY_PATH来实现
SELECT t.ID, SYS_CONNECT_BY_PATH(t.NAME, ‘\’) AS INDU_NAME
FROM TREETEST t
START WITH t.PID IS NULL
CONNECT BY PRIOR t.ID = t.PID
FROM TREETEST t
START WITH t.PID IS NULL
CONNECT BY PRIOR t.ID = t.PID
查询结果如下:
4、同理,也可以从下往上进行查询
SELECT *
FROM TREETEST t
START WITH t.ID=8
CONNECT BY t.ID = PRIOR t.PID
FROM TREETEST t
START WITH t.ID=8
CONNECT BY t.ID = PRIOR t.PID
到此这篇关于一文解析ORACLE树结构查询的文章就介绍到这了,更多相关ORACLE树结构查询内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!