在 Postgres 中递归获取树的根 ID table

Recursively getting a root ID of tree in Postgres table

我有一个 Postgres table users (E_8_User),其中包含 User_id 作为主键,Boss 作为相同 table 的外键(它是不可为空,如果某些用户没有老板,则其老板属性 = user_id)。 我需要为 table 中的所有用户找到他们的老板,所以我正在尝试编写 CTE 查询:

WITH RECURSIVE
herarchy_reports AS
(
SELECT E_8_User.User_id, E_8_User.Boss, 1 as lvl,
E_8_User.User_id as RootUserID
FROM E_8_User
WHERE E_8_User.User_id=E_8_User.Boss
UNION ALL
SELECT usr.User_id, usr.Boss, lvl+1 as lvl,
rep.RootUserID
FROM herarchy_reports as rep JOIN E_8_User as usr ON
rep.user_id=usr.Boss
)
SELECT * FROM herarchy_reports ORDER BY RootUserID;

但它不起作用:数据库一直在执行查询。 我究竟做错了什么?

这是一个典型的递归查询:

with recursive cte as (
    select u.user_id, u.boss, 1 as lvl from e_8_user u
    union all
    select u.user_id, c.boss, lvl + 1
    from cte c 
    inner join e_8_user u on u.boss = c.user_id and u.user_id != c.user_id
)
select user_id, boss 
from cte c
where lvl = (select max(c1.lvl) from cte c1 where c1.user_id = c.user_id) 
order by user_id

在递归查询中,技巧是当记录与自身连接时停止递归 (u.boss = c.user_id and u.user_id != c.user_id)。

然后,在外层查询中,你想select每个用户的级别最高的记录。

假设样本数据如下:

user_id | boss
------: | ---:
      1 |    1
      2 |    1
      3 |    2
      4 |    3
      5 |    2
      6 |    6
      7 |    6

查询产生:

user_id | boss
------: | ---:
      1 |    1
      2 |    1
      3 |    1
      4 |    1
      5 |    1
      6 |    6
      7 |    6

Demo on DB Fiddle