尝试将返回表的postgres函数组合为1个返回json的函数

li9yvcax  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(109)

我有多个函数,它们都返回表中相同的数据结构。我有一个函数,它通过UNION调用所有函数,并以表格格式返回结果。我如何让这一个函数返回json中所有子函数的结果?
我试着做:

SELECT row_to_json(t) from (select col1, col2, col3 from db.subfunction1())
UNION
SELECT row_to_json(t) from (select col1, col2, col3 from db.subfunction2())
UNION
SELECT row_to_json(t) from (select col1, col2, col3 from db.subfunction3());

并且得到了
错误:无法标识类型json的相等运算符行1:选择row_to_json(t)从(选择..........^SQL状态:42883人物:8
好的,我运行以下代码:从db.subfunction1()中选择 *;
结果是一个表
| 资料类型|约会|一些文本|另一个文本字段|
| - ------|- ------|- ------|- ------|
| 一些东西|2021年1月31日|详细信息|IP4:5663773;|
每个函数都做同样的事情,我希望父函数将输出转换为JSON。

9o685dep

9o685dep1#

您的问题仍然很不清楚,但让我们尝试在3个联合的结果上重复row_to_json()

WITH abc as (
   SELECT 'Something' as col1,  '2021-01-31' as col2,   'detail info' as col3),
  def as (
   select 1 as i,row_to_json(abc) as j from abc
     union all
   select 2,row_to_json(abc) from abc
     union all
   select 3,row_to_json(abc) from abc
  )
select row_to_json(x) from (
select def.j as a, d2.j as b, d3.j as c
from def
inner join def d2 on d2.i=2
inner join def d3 on d3.i=3 
where def.i=1) x;

参见:DBFIDDLE
结果:

{"a":{"col1":"Something","col2":"2021-01-31","col3":"detail info"},"b":{"col1":"Something","col2":"2021-01-31","col3":"detail info"},"c":{"col1":"Something","col2":"2021-01-31","col3":"detail info"}}

相关问题