oracle 递归查询_Oracle递归查询

一、创建数据

1.1、建立表与插入数据

CREATE TABLE DISTRICT(  ID         NUMBER(10)                  NOT NULL,  PARENT_ID  NUMBER(10),  NAME       VARCHAR2(255 BYTE)          NOT NULL);ALTER TABLE DISTRICT ADD (  CONSTRAINT DISTRICT_PK PRIMARY KEY (ID));ALTER TABLE DISTRICT ADD (  CONSTRAINT DISTRICT_R01  FOREIGN KEY (PARENT_ID)  REFERENCES DISTRICT (ID));   insert into DISTRICT (id, parent_id, name)values (1, null, '四川省');insert into DISTRICT (id, parent_id, name)values (2, 1, '巴中市');insert into DISTRICT (id, parent_id, name)values (3, 1, '达州市');insert into DISTRICT (id, parent_id, name)values (4, 2, '巴州区');insert into DISTRICT (id, parent_id, name)values (5, 2, '通江县');insert into DISTRICT (id, parent_id, name)values (6, 2, '平昌县');insert into DISTRICT (id, parent_id, name)values (7, 3, '通川区');insert into DISTRICT (id, parent_id, name)values (8, 3, '宣汉县');insert into DISTRICT (id, parent_id, name)values (9, 8, '塔河乡');insert into DISTRICT (id, parent_id, name)values (10, 8, '三河乡');insert into DISTRICT (id, parent_id, name)values (11, 8, '胡家镇');insert into DISTRICT (id, parent_id, name)values (12, 8, '南坝镇');insert into DISTRICT (id, parent_id, name)values (13, 6, '大寨乡');insert into DISTRICT (id, parent_id, name)values (14, 6, '响滩镇');insert into DISTRICT (id, parent_id, name)values (15, 6, '龙岗镇');insert into DISTRICT (id, parent_id, name)values (16, 6, '白衣镇');commit;
53aa5927449d2b982093ff86d07eff3b.png

二、start with connect by prior递归

2.1、查询所有子节点

SELECT *FROM districtSTART WITH NAME ='巴中市'CONNECT BY PRIOR ID=parent_id
a1940402cef60dea586a378bcd8d1c28.png

2.2、查询所有父节点

SELECT *FROM districtSTART WITH NAME ='平昌县'CONNECT BY PRIOR parent_id=ID

只需要交换 id 与parent_id的位置即可

ce341776a2b3b897fc9d6667faa15b36.png

2.3、查询指定节点的,根节点

SELECT d.*,connect_by_root(d.id),connect_by_root(NAME)FROM district dWHERE NAME='平昌县'START WITH d.parent_id=1    --d.parent_id is null 结果为四川省CONNECT BY PRIOR d.ID=d.parent_id
4ae08eacc8fd36952018fda4d8fb6462.png

2.4、查询巴中市下行政组织递归路径

SELECT ID,parent_id,NAME,sys_connect_by_path(NAME,'->') namepath,LEVELFROM district START WITH NAME='巴中市'CONNECT BY PRIOR ID=parent_id
fb73fa2a076529be17f5de1fe7dcf524.png

三、with递归

3.1、with递归子类

WITH t (ID ,parent_id,NAME) --要有列名AS(SELECT ID ,parent_id,NAME FROM district WHERE NAME='巴中市'UNION ALLSELECT d.ID ,d.parent_id,d.NAME FROM t,district d --要指定表和列表,WHERE t.id=d.parent_id)SELECT * FROM t;
b20b78e07fc32193e6a1dae738d51fb6.png

3.2、递归父类

WITH t (ID ,parent_id,NAME) --要有表AS(SELECT ID ,parent_id,NAME FROM district WHERE NAME='通江县'UNION ALLSELECT d.ID ,d.parent_id,d.NAME FROM t,district d --要指定表和列表,WHERE t.parent_id=d.id)SELECT * FROM t;
286ffe50ef9c700d05874f0d5b28c39e.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值