簡體   English   中英

Oracle中的分層查詢

[英]Hierarchical queries in Oracle

我在Oracle11g中有一個具有(id,parent_id)結構的表。

id    parent_id
---------------
1     (null)
2     (null)
3     1
4     3
5     3
6     2
7     2

我想對其進行查詢,以獲取與這些ID各自分層鏈接的所有行,因此結果應為:

root_id  id    parent_id
------------------------
1        3     1
1        4     3
1        5     3
2        6     2
2        7     2
3        4     3
3        5     3

我一直在努力進行connect bystart with現在start with已經有一段時間了,而我所能獲得的只是查詢所需結果的一小部分:

select connect_by_root(id) root_id, id, parent_id from my-table
start with id=1
connect by prior id = parent_id

我不想使用任何for循環來獲取完整的結果。

任何想法 ?

此致JérômeLefrère

PS:在第一個答案后編輯,注意到我忘記了一些我想要的結果...

您發布的查詢缺少from子句,並在connect_by_root保留了下划線,但是我認為這些實際上並不是問題的根源。

以下查詢為您提供所需的結果:

select * from (
   select connect_by_root(id) root_id, id, parent_id
   from test1
   start with parent_id is null
   connect by prior id = parent_id)
where root_id <> id

中心問題是您要指定一個特定的起始值,而不是指定一種識別根行的方法。 id = 1更改為parent_id is null可以返回表的全部內容。

我還添加了外部查詢,以從結果集中過濾出根行,這在您的問題中沒有提到,但已顯示在您想要的結果中。

SQL小提琴示例


評論回應:

在提供的版本中,您確實獲得了id = 3后代,但並非以3為根。 這是因為我們從絕對根開始。 解決這個問題很容易,只需省略start with子句:

SELECT *
FROM
  (SELECT connect_by_root(id) root_id,
          id,
          parent_id
   FROM test1
CONNECT BY
   PRIOR id = parent_id)
WHERE root_id <> id

SQL小提琴示例

嘗試這個:

select connect_by_root(id) root_id, id, parent_id
from your_table
start with parent_id is null
connect by prior id = parent_id

它會為您提供所需的確切結果:

select connect_by_root(id) as root, id, parent_id
from test1
connect by prior id=parent_id
start with parent_id is not null;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM