Oracle_start_with_connect_by_prior_用法
語法:
select *
from 表名
where 條件1
start with 條件2
connect by prior 當前表字段=級聯表字段
start with與connect by prior語句完成遞迴記錄,形成一棵樹形結構,通常可以在具有層次結構的表中使用。
start with表示開始的記錄
connect by prior 指定與當前記錄關聯時的欄位關係
程式碼:
--建立部門表,這是一個具有層次結構的表,子記錄通過parent_id與父記錄的id進行關聯create table DEPT(
ID NUMBER(9) PRIMARY KEY, --部門ID
NAME VARCHAR2(100), --
部門名稱PARENT_ID NUMBER(9) --父級部門ID,通過此欄位與上級部門關聯
);
向表中插入如下資料,為了使程式碼簡單,一個部門僅具有一個下級部門
●從根節點開始查詢遞迴的記錄
select *
from dept
start with id=1
connect by prior id = parent_id; 下面是查詢結果,start withid=1表示從id=1的記錄開始查詢,向葉子的方向遞迴,遞迴條件是id=parent_id,當前記錄的id等於子記錄的parent_id ●從葉子節點開始查詢遞迴的記錄
select *
from dept
start with id=5
connect by prior parent_id = id;
下面是查詢結果,遞迴條件按照當前記錄的parent_id等與父記錄的id
●對查詢結果過濾
select *
from dept
where name like '%銷售%'
start with id=1
connect by prior id = parent_id;
在下面的查詢結果中可以看到,首先使用start with... connect by prior查詢出樹形的結構,然後where條件才生效,對全部查詢結果進行過濾
●prior的作用 prior關鍵字表示不進行遞迴查詢,僅查詢出滿足id=1的記錄,下面是將第一個查詢去掉prior關鍵字後結果
select *
from dept
start with id=1
connect by prior id = parent_id;