简体   繁体   English

postgres 中的递归自连接

[英]Recursive Self-Join in postgres

I have a table of profiles that have data related to the managers of a user.我有一个profiles表,其中包含与用户经理相关的数据。

There can multiple levels of managers for a user.一个用户可以有多个级别的管理员。

I need to write a query to get all the managers of a user.我需要编写一个查询来获取用户的所有管理员。

Official manager_id is stored in column text = A .官方manager_id存储在列text = A中。

Table Name profiles表名称profiles

id ID text文本 manager_id manager_id user_id用户身份
1 1个 A一种 20 20 50 50
2 2个 B 20 20 50 50
3 3个 A一种 21 21 20 20
4 4个 B NULL NULL 20 20
5 5个 C C NULL NULL 20 20
6 6个 A一种 22 22 21 21
7 7 B NULL NULL 21 21
9 9 A一种 NULL NULL 22 22

For example,例如,

If user_id=50 then,如果user_id=50那么,
50 manager's is 20 50经理就是20
20 manager's is 21 20经理是21
21 manager's is 22 21经理是22
21 manager's is NULL 21经理的是NULL
So, the output should be 20,21,22所以,output 应该是20,21,22

Similarly, if user_id=20 the output should be 21,22同样,如果user_id=20 output 应该是21,22

I tried a couple of queries but it doesn't return the expected output.我尝试了几个查询,但没有返回预期的 output。

The recursive query you're looking for should feature:您正在寻找的递归查询应该具有:

  • base step, which begins with distinct couples of user_id and manager_id from the input table基本步骤,以输入表中不同的 user_id 和 manager_id 对开始
  • recursive step, which self joins the table with the current recursive result, matching manager of the second to be users of the first递归步骤,将表与当前递归结果自连接,将第二个的经理匹配为第一个的用户

Once you get all matches, you can aggregate your values by " user_id " with ARRAY_AGG .获得所有匹配项后,您可以通过“ user_id ”和ARRAY_AGG聚合您的值。

WITH RECURSIVE cte AS (
    SELECT DISTINCT user_id, manager_id 
    FROM tab 
    WHERE manager_id IS NOT NULL
  
    UNION ALL
  
    SELECT usr.user_id,
           mgr.manager_id
    FROM       cte usr
    INNER JOIN tab mgr
            ON usr.manager_id = mgr.user_id
    WHERE mgr.manager_id IS NOT NULL
)
SELECT user_id, 
       ARRAY_AGG(manager_id) AS managers
FROM cte 
GROUP BY user_id

Check the demo here .此处查看演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM