程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle教程 >> Oracle遞歸查詢

Oracle遞歸查詢

編輯: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;

 

二、start with connect by prior遞歸   2.1、查詢所有子節點  
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 d
WHERE 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,
LEVEL
FROM 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 ALL
SELECT 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 ALL
SELECT d.ID ,d.parent_id,d.NAME FROM t,district d --要指定表和列表,
WHERE t.parent_id=d.id
)
SELECT * FROM t;

 


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved