[英]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 ![]() |
text![]() |
manager_id ![]() |
user_id![]() |
---|---|---|---|
1 ![]() |
A![]() |
20 ![]() |
50 ![]() |
2 ![]() |
B![]() |
20 ![]() |
50 ![]() |
3 ![]() |
A![]() |
21 ![]() |
20 ![]() |
4 ![]() |
B![]() |
NULL ![]() |
20 ![]() |
5 ![]() |
C ![]() |
NULL ![]() |
20 ![]() |
6 ![]() |
A![]() |
22 ![]() |
21 ![]() |
7 ![]() |
B![]() |
NULL ![]() |
21 ![]() |
9 ![]() |
A![]() |
NULL ![]() |
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:您正在寻找的递归查询应该具有:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.