psqljsonb数组

vd2z7a6w  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(280)

我的数据结构就像数组中的数组。我有一个名为id(int)、meta(jsonb)的2列表,其中存储的数据如下:

id : meta
12 : [... ]

[…]如下所示:

[
  {
    "task": "T3",
    "task_label": "what is wrong.",
    "value": "Something's wrong"
  },
  {
    "task": "T0",
    "task_label": "What's wrong about this image?",
    "value": [
      {
        "x": 228.52696228027344,
        "y": 42.95765686035156,
        "tool": 0,
        "frame": 0,
        "width": 738.8717193603516,
        "height": 45.10553741455078,
        "details": [],
        "tool_label": "Sender"
      },
      {
        "x": 1302.4683837890625,
        "y": 642.2169799804688,
        "tool": 2,
        "frame": 0,
        "width": 423.1329345703125,
        "height": 115.98565673828125,
        "details": [],
        "tool_label": "Action"
      }
    ]
  }
]

我想运行sql查询来查找task=“t0”所在的所有工具标签的列表。
结果应该是

id: meta->task->value->tool_label
12: Sender, Action
hmtdttj4

hmtdttj41#

你可以用 jsonb_array_elements() 两次,然后过滤和聚合:

select t.id, string_agg(l2.obj ->> 'tool_label', ',') tool_labels
from mytable t
cross join lateral jsonb_array_elements(t.meta)            as l1(obj)
cross join lateral jsonb_array_elements(l1.obj -> 'value') as l2(obj)
where l1.obj ->> 'task' = 'T0'
group by t.id

相关问题