[英]Oracle hierarchical queries data
The link gives a good example for overview on how to use Oracle hierarchical queries.该链接提供了一个很好的示例,用于概述如何使用 Oracle 分层查询。 I was trying to generate the below combination of data with the example table
tab1
given in the link but struck for a while.Using Oracle version 12.2我试图使用链接中给出的示例表
tab1
生成以下数据组合,但敲了一段时间。使用 Oracle 版本 12.2
PARENT_ID CHILD_ID
-------- ---------
1 2 # the root node and id combination (This is evident by using ROOT_ID,ID)
1 3
1 4
. .
. .
2 5 # How to generate below combination in a select statement ont TAB1 table.
2 6
. .
. .
9 11
SELECT id,
parent_id,
RPAD('.', (level-1)*2, '.') || id AS tree,
level,
CONNECT_BY_ROOT id AS root_id,
LTRIM(SYS_CONNECT_BY_PATH(id, '-'), '-') AS path,
CONNECT_BY_ISLEAF AS leaf
FROM tab1
START WITH parent_id IS NULL
CONNECT BY parent_id = PRIOR id
ORDER SIBLINGS BY id;
Output of the above select statement上述select声明的Output
ID PARENT_ID TREE LEVEL ROOT_ID PATH LEAF
---------- ---------- -------------------- ---------- ---------- -------------------- ----------
1 1 1 1 1 0
2 1 ..2 2 1 1-2 0
3 2 ....3 3 1 1-2-3 1
4 2 ....4 3 1 1-2-4 0
5 4 ......5 4 1 1-2-4-5 1
6 4 ......6 4 1 1-2-4-6 1
7 1 ..7 2 1 1-7 0
8 7 ....8 3 1 1-7-8 1
9 1 ..9 2 1 1-9 0
10 9 ....10 3 1 1-9-10 0
11 10 ......11 4 1 1-9-10-11 1
12 9 ....12 3 1 1-9-12 1
The sql query to get the desired output are below:获取所需 output 的 sql 查询如下:
Solution 1: using CTE解决方案 1:使用 CTE
with h ( id, parent_id ) as (
select id ,parent_id from tab1
),
r ( id , parent_id, steps ) as (
select id , id , 0
from h
union all
select r.id, h.parent_id, steps + 1
from h join r
on h.id = r.parent_id
)
select parent_id, id
from r
where parent_id != id
order by parent_id asc;
Solution 2: Using Oracle only connect by query.解决方案 2:使用 Oracle 仅通过查询连接。 The CONNECT BY NOCYCLE clause can be used to not traverse cyclical hierarchies if any.
CONNECT BY NOCYCLE 子句可用于不遍历循环层次结构(如果有)。
with hier_data as
(
select
connect_by_root id as parent_id
,id
from tab1
connect by parent_id = prior id
order by parent_id,id
)
select * from hier_data
where
parent_id != id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.