pgsql 合并两个 json 数组

问题描述

我必须从表中选择两种类型的结果集并将它们合并到单个 json 数组中 喜欢

select col1,col2,col3 from table 1 order by col3 where col1< 2
union all 
select col1,col3 from table 1 order by col1 where colo = 3

我认为这是由于 order by 导致的语法错误

我需要在 json 数组中返回它,所以我正在尝试这样

SELECT (    SELECT json_agg(row)
            FROM (
         select col1,col3 from table 1 order by col3 where col1< 2 ) row)
UNION ALL
  SELECT (SELECT json_agg(row)
            FROM (
        select col1,col3 from table 1 order by col1 where colo = 3
) row)

它正在停用两个 json 数组,即很明显,我怎样才能在单个数组中做到这一点

谢谢,

解决方法

在 UNION 之后进行聚合:

select json_agg(t)
from (
  (select col1,col2,col3 from table1 order by col3 where col1< 2)
  union all 
  (select col1,col3 from table1 order by col1 where colo = 3)
) t