首页 > 解决方案 > 如何从 postgres 函数返回两个 SELECT 语句的结果?

问题描述

我有这个 postgresql 函数:

CREATE OR REPLACE FUNCTION public.test_q1()
 RETURNS TABLE(schemaname text)
 LANGUAGE plpgsql
AS $function$
BEGIN
   return Query (select "content" from public.post where id='863550630468626253');
  -- return Query (select count(*) from public.comments WHERE post_id='863550630468626253');
END
$function$
;

如何从此函数返回两个 select 语句结果?

是否可以从函数返回两个语句的结果集,select这样当我调用public.test_q1它时将返回两个值,第一个结果集将是content第一个和第二个返回值内的其他列的Select值?

标签: sqlpostgresql

解决方案


在一个查询中返回两个值?

 select p."content",
        (select count(*)
         from public.comments c
         where c.post_id = '863550630468626253'
        ) as num_comments
 from public.post p
where p.id = '863550630468626253'
            );

编辑:

我认为您不能保证函数返回集中结果的顺序,但您可以使用它union all来返回两个值。想必,content不是一个数字。因此,一种方法是转换值:

 select p."content"
 from public.post p
 where p.id = '863550630468626253'
 union all
 select count(*)::text
 from public.comments c
 where c.post_id = '863550630468626253';

我相信在实践中这将首先返回内容,然后返回计数。但是,我认为 Postgres 不能保证排序。


推荐阅读