【问题标题】:How to return result of two SELECT statement from a postgres fuunction?如何从 postgres 函数返回两个 SELECT 语句的结果?
【发布时间】:2019-04-14 22:48:39
【问题描述】:

我有这个 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 内的其他列的值第二个返回值将是计数?

【问题讨论】:

  • “两个输出”是什么意思?两排?两列?

标签: sql postgresql


【解决方案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 不能保证排序。

【讨论】:

  • 是否可以从函数返回两个select 语句输出,这样当我调用public.test_q1 时它会返回两个输出?
  • @manish 。 . .我不明白你的评论。你想要两行而不是两列吗?如果是这样,请使用union all
猜你喜欢
  • 2019-12-23
  • 2011-02-16
  • 2012-05-19
  • 2021-12-08
  • 1970-01-01
  • 2013-06-30
  • 2019-08-30
  • 2011-02-19
相关资源
最近更新 更多