PRIOR僅從遍歷層次結構中的先前記錄獲取記錄。
我認爲已瞭解它是如何工作的最好方式是用一個簡單的層次發揮:
create table qwerty(
id int,
name varchar2(100),
parent_id int
);
insert all
into qwerty values(1, 'Grandfather', null)
into qwerty values(2, 'Father', 1)
into qwerty values(3, 'Son', 2)
into qwerty values(4, 'Grandson', 3)
select 1234 from dual;
下面的查詢遍歷以上層次:
select level, t.*
from qwerty t
start with name = 'Grandfather'
connect by prior id = parent_id
LEVEL ID NAME PARENT_ID
---------- ---------- -------------------- ----------
1 1 Grandfather
2 2 Father 1
3 3 Son 2
4 4 Grandson 3
如果再加上「此前名」來上面的查詢,然後顯示「父」的名稱。該值取自層次結構中的prevoius記錄(來自LEVEL-1)
select level, prior name as parent_name, t.*
from qwerty t
start with name = 'Grandfather'
connect by prior id = parent_id;
LEVEL PARENT_NAME ID NAME PARENT_ID
---------- -------------------- ---------- -------------------- ----------
1 1 Grandfather
2 Grandfather 2 Father 1
3 Father 3 Son 2
4 Son 4 Grandson 3