如何从postgres函数返回两个SELECT语句的结果?

问题描述 投票:0回答:1

我有这个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时它将返回两个值,第一个resultset将是content的值和第一个Select中的其他列,第二个返回值将是计数?

sql postgresql
1个回答
1
投票

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

 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保证订购。

© www.soinside.com 2019 - 2024. All rights reserved.