我不明白它向查询结果添加了什么。从我正在学习的书中:
If you prefix a column name with PRIOR in the select list (SELECT PRIOR EMPLOYEE_ID, ...), you specify the “prior” row’s value.
SELECT PRIOR EMPLOYEE_ID, MANAGER_ID, LPAD(' ', LEVEL * 2) || EMPLOYEES.JOB_ID
FROM EMPLOYEES
START WITH EMPLOYEE_ID = 100
CONNECT BY PRIOR EMPLOYEE_ID = MANAGER_ID;
我看到的唯一区别是,它在第一行添加了一个 NULL
值并将员工 ID 递增 1。
最佳答案
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
如果我们在上述查询中添加“PRIOR name”,则会显示“parent”的名称。此值取自层次结构中的 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
关于sql - 在 SELECT 列表中优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826092/