[英]How to get the list of parent and Child in a Hierarchy using Oracle SQL
我有兩個表,相同的結構如下:
表1 。 交易數據表
trx id.
1
2
3
4
5..etc
表2表2具有如下的父子關系。
id subject_id (Child) object_id (Parent)
1 2 1
2 3 1
3 4 1
4 5 1
現在使用上表,預期輸出如下:
1
2
3
4
5
請讓我知道我如何能達到同樣的效果。 我需要從表1中獲取詳細信息以及父級及其在層次結構中的所有子級。 我只有一個層次結構。
由於您只有一個層次結構,因此可以正確地對結果進行排序,使其正常工作。 試試這個:
select obj.object_id, t.*
from
(
select
object_id,
object_id as parent_id
from table2
union
select
subject_id as object_id,
object_id as parent_id
from table2
) obj
inner join table1 t
on t.id = obj.object_id
order by
obj.parent_id,
case when obj.object_id = obj.parent_id then 0 else 1 end,
obj.object_id
;
我對@a_horse的評論有所不同...
select * from table1
where id in
(select object_id from table2
union all
select subject_id from table2)
order by id;
符合預期
1
2
3
4
5
如果要約束父級,只需在子查詢中添加WHERE謂詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.