【问题标题】:Extract a sub-tree from a hierarchy tree based on a leaf in Oracle基于Oracle中的叶子从层次树中提取子树
【发布时间】:2021-05-19 11:24:04
【问题描述】:

我有一个表 users 代表这样的分层树:

Column Type Comment
user_id integer sequence
user_type integer 1 for group of users 2 for normal user
group_id integer Reference to a user in the same table with user_type = 1
user_name varchar(xxx)

group_id 列引用另一个 user_id,以便将组和用户存储在同一个表中。

master group_id 为 0。

像这样:

user_id user_type group_id user_name
0 1 null 'All users'
5 2 0 'USER1'
6 2 0 'USER2'
11 1 0 'SUBGROUP1'
12 1 11 'SUBGROUP2'
13 2 12 'USER3'
20 1 0 'SUBGROUP3'
21 2 20 'USER4'

注意:

  • user_id 中可能存在空白。
  • 一个组可以不包含任何内容,也可以包含任意数量的组或用户。

我已经设法使用connect by oracle 语句检索完整的树,并正确缩进和排序。

这不是我的问题。

我的问题是:

给定一个查询的 user_id,如何浏览树到主组“所有用户” 并输出从叶子到主组的完整路径?

示例 1:我为 USER1 运行查询,我想要以下输出:

All Users
- USER1

示例 2:我对 USER3 运行相同的查询,我想要以下输出:

All Users
- SUBGROUP1
-- SUBGROUP2
--- USER3

我希望有人可以帮助我。

有关信息,我发布查询以检索完整树,以便您查看 connect by 和 start with 的使用。 我确信这个查询与我想要的很接近,但我的尝试永远不会产生我想要的结果。

select 
  lpad('-', (level - 1) * 2, ' ') || u.user_name as padded_name, 
  u.userid, 
  u.user_group, 
  u.user_type,
  level
from users u
connect by prior u.user_id = u.group_id
start with u.user_id = 0
order siblings by upper(u.user_name);

【问题讨论】:

    标签: oracle tree hierarchical-data connect-by


    【解决方案1】:

    您可以使用connect by 朝相反的方向行走。那么level 当然也会相反。因此,要以正确的顺序和缩进获得结果,请根据这些结果链接另一个查询,该查询将使用row_number() 来确定缩进:

    with base as (
      select 
        u.user_name,
        u.user_id, 
        u.group_id, 
        u.user_type,
        level as lvl
      from users u
      connect by prior u.group_id = u.user_id
      start with u.user_id = 13
    )
    select 
      lpad('-', (row_number() over (order by lvl desc) - 1) * 2, ' ') || base.user_name
        as padded_name,
      user_id,
      group_id,
      user_type
    from base
    order by lvl desc;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-18
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2013-01-19
      • 2017-03-17
      相关资源
      最近更新 更多