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;
二、start with connect by prior递归
查询所有子节点
SELECT *
FROM district
START WITH NAME ='巴中市'
CONNECT BY PRIOR ID=parent_id
2.2、查询所有父节点
SELECT *
FROM district
START WITH NAME ='平昌县'
CONNECT BY PRIOR parent_id=ID
只需要交换 id 与parent_id的位置即可
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
2.4、查询巴中市下行政组织递归路径
SELECT ID,parent_id,NAME, sys_connect_by_path(NAME,'->') namepath,LEVELFROM district START WITH NAME='巴中市'CONNECT BY PRIOR ID=parent_id
三、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;
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;
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享题目:Oracle递归查询-创新互联
文章出自:http://myzitong.com/article/cojsih.html