【问题标题】:Could not merge multiple Jsonb rows into a single row无法将多个 Jsonb 行合并为一行
【发布时间】:2020-08-08 21:12:57
【问题描述】:

需要合并我的单个 jsonb 列的所有行。

例如:我的 jsonb 列的行如下所示。

我的输入数据是(2行):

{"room": ["101"],"equipments": ["thermometer"]}
{"room": ["101","102"], "equipments": ["stethescope"]}

在运行此查询时,

select (jsonb_each(jsonbcolumn)).* 
from table group by key, value

我得到以下输出,

    key         |       value
    equipments  |     ["stethescope"] 
    equipments  |     ["thermometer"]
    room        |     ["101","102"] 
    room        |     ["101"]

如果我尝试使用 jsonb_object_agg 按键添加值,jsonb 会消除第一个值并仅保留第二个值。

{"room": ["101","102"],"equipments": ["stethescope"]}

如果我尝试使用 json_object_agg,我会得到重复值

{ "room" : ["101"], "equipments" : ["thermometer"], "room" : ["101", "102"], "equipments" : ["stethescope"] }

我的预期输出是

{"room": ["101","102"], "equipments":["stethescope", "thermometer"]}

在一行中。

尝试了几乎所有网络中的解决方案。这是我尝试过的几个链接。

【问题讨论】:

    标签: json postgresql concatenation jsonb merging-data


    【解决方案1】:

    我能想到的唯一解决方案是:

    select jsonb_build_object(
              'room', jsonb_agg(distinct r.room), 
              'equipments', jsonb_agg(distinct e.equipment) 
           )
    from data d
      cross join jsonb_array_elements_text(d.jsonbcolumn -> 'room') as r(room)
      cross join jsonb_array_elements_text(d.jsonbcolumn -> 'equipments') as e(equipment)
    

    但这将是极其低效的(但这就是你为去规范化付出的代价)

    Online example

    【讨论】:

      猜你喜欢
      • 2014-06-19
      • 2012-08-29
      • 2012-12-29
      • 1970-01-01
      相关资源
      最近更新 更多