【发布时间】:2021-01-08 22:07:11
【问题描述】:
我有一个数据库,其中包含维护有关用户和其他允许批准这些用户的任务的用户的信息的表。此审批者可以是用户的主管(维护在users 表的一对多关系中),或另一个明确授予审批权限的用户(维护在单独的多对多关系表中)。
我的目标是为给定用户(即,允许该用户批准的对象,以及这些批准者的批准链中的任何人)找到完整的“批准者”树(或链)。由于上面描述的“显式其他批准者”的多对多关系,这不像查找WHERE u1.username = u2.supervisor那么简单,所以这不像这里给出的示例那么简单:https://www.postgresqltutorial.com/postgresql-recursive-query/
对于非递归的情况,我编写了一个函数,允许我让所有用户被某个用户批准,看起来像这样(它还做了一些其他的事情,比如根据信息保存在另一个表中,但它的核心位是子查询中union 两侧的内容):
CREATE OR REPLACE FUNCTION public.get_user_approvees(username text)
RETURNS TABLE(approvee_username text, approvee_name text, approver_username text)
LANGUAGE plpgsql
AS $function$
#variable_conflict use_variable
BEGIN
return query
-- with the below subquery, select the username and get names from preferences for
-- the approvee
select sq.approvee, up.first_name || ' ' || up.last_name, username as "name" from
(
-- get the approvees of the users group as a subquery
select u2.username as approvee from group_approvers ga
inner join users u2 on u2.group_id = ga.group_id
where ga.approver = username
and u2.username != username
and u2.is_active
union
-- add any other users this user is directly responsible for
select ua.approvee from user_approvers ua
inner join users u on u.username = ua.approvee
where ua.approver = username
and u.is_active
) as sq
inner join users u on sq.approvee = u.username
inner join user_preferences up on u.user_prefs = up.id;
END;
$function$
;
我认为基于此,我应该能够非常简单地编写一个执行相同操作但递归的函数。但是我的尝试不起作用,我想知道(1)为什么? (2) 我怎样才能做到这一点?
这是我对递归 CTE 函数的尝试:
CREATE OR REPLACE FUNCTION public.recursive_test(username text)
RETURNS TABLE(approvee_username text, approvee_name text, approver_name text)
LANGUAGE plpgsql
AS $function$
#variable_conflict use_variable
BEGIN
return query
WITH RECURSIVE all_approvees AS (
(
SELECT * FROM get_user_approvees(username)
)
UNION
(
SELECT * FROM get_user_approvees(all_approvees.approvee)
)
) SELECT
*
FROM all_approvees;
END;
$function$
;
当我尝试运行此函数时,我在运行时收到一条错误消息:
ERROR: missing FROM-clause entry for table "all_approvees"
LINE 7: SELECT * FROM get_user_approvees(all_approvees.approve...
有什么想法吗?
【问题讨论】:
标签: sql postgresql recursion sql-function