如何在postgresql中合并json字段和对象数组

3duebb1j  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(260)

如何合并

[{"k": 1,"v":{"a1": null}}, {"k": 2, "v":{"b1":"B1"}}, {"k": 3, "v":{"c1":"C1"}}]

[{"k": 1,"v":{"a1": "A1"}}, {"k": 2, "v":{"b1":"B1", "b2": "B2"}}]

字符串
预期结果@

[{"k": 1,"v":{"a1": "A1"}}, {"k": 2, "v":{"b1":"B1", "b2": "B2"}}, {"k": 3, "v":{"c1":"C1"}}]


我尝试了以下一个:

WITH merged_objects AS (
  SELECT k,
         jsonb_agg(v) as v
  FROM (
    SELECT elem -> 'k' as k,
           jsonb_each(elem -> 'v') as v
    FROM (
      SELECT jsonb_array_elements('[
        {"k": 1, "v": {"a1": null}},
        {"k": 2, "v": {"b1": "B1"}},
        {"k": 3, "v": {"c1": "C1"}}
      ]'::jsonb) as elem

      UNION ALL

      SELECT jsonb_array_elements('[
        {"k": 1, "v": {"a1": "A1"}},
        {"k": 2, "v": {"b1": "B1", "b2": "B2"}}
      ]'::jsonb) as elem
    ) subquery
  ) subquery
  GROUP BY k
)
SELECT jsonb_agg(jsonb_build_object('k', k, 'v', v)) as merged_array
FROM merged_objects;


但结果不对。v字段中的值尚未合并。

[{"k": 2, "v": [{"key": "b1", "value": "B1"}, {"key": "b1", "value": "B1"}, {"key": "b2", "value": "B2"}]}, {"k": 1, "v": [{"key": "a1", "value": null}, {"key": "a1", "value": "A1"}]}, {"k": 3, "v": [{"key": "c1", "value": "C1"}]}]

x6h2sr28

x6h2sr281#

可以使用||运算符合并JSONB值。下面是一个例子。请注意,使用coalesce处理不匹配的JSON密钥。

select jsonb_agg(coalesce(j1, '{}') || coalesce(j2, '{}')) as merged_array
from
  jsonb_array_elements('[{"k":1,"v":{"a1":null}},{"k":2,"v":{"b1":"B1"}},{"k":3,"v":{"c1":"C1"}}]'::jsonb) j1 
left outer join
  jsonb_array_elements('[{"k":1,"v":{"a1":"A1"}},{"k":2,"v":{"b1":"B1","b2":"B2"}}]'::jsonb) j2 
on (j1 ->> 'k') = (j2 ->> 'k');

字符串
答案已编辑。您也可以将上面的查询用作标量子查询。
DB-fiddle
| merged_array |
| ------------ |
| {“a1”:“A1”}},{“k”:2、“v”:{“b1”:“B1”、“B2”:“B2”}},{“k”:3、“v”:{“c1”:“C1”}}] "C1"}}] |

相关问题