【问题标题】:How to filter json array per each returned row in Postgresql如何在 Postgresql 中为每个返回的行过滤 json 数组
【发布时间】:2020-02-05 07:06:43
【问题描述】:

如果对象结构是这样的,你能帮我吗,

我有一个带有 JSON 字段的表,其中存储了一个对象数组。我想查询这个表,并且对于每个返回的行,通过使用某些条件过滤它们,只返回 json 数组对象的子集。

例如对于行:

id = 1, jsonColumn = [{ field: 'abc', Observation: [Value: 'Value1'] },{ field: 'def', Observation: [Value: 'Value2'] },{ field: 'ghi, Observation: [Value: 'Value3']' }]
id = 2, jsonColumn = [{ field: 'pqr', Observation: [Value: 'Value1'] },{ field: 'aaa', Observation: [Value: 'Value2'] },{ field: 'ccc, Observation: [Value: 'Value3']' }]
id = 3, jsonColumn = [{ field: 'www', Observation: [Value: 'Value1'] },{ field: 'qqq', Observation: [Value: 'Value2'] },{ field: 'rrr', Observation: [Value: 'Value3']' }]

我想选择所有行,并且每行应在 jsonColumn 中仅包含字段 = 'abc' 和 Value = 'Value1' 的元素。我只想过滤此列,而不是返回包含数组中特定元素的行...

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    您可以使用子选择和json_array_elements,然后是aggregated back to an array

    SELECT
      id,
      ( SELECT json_agg(element)
        FROM json_array_elements(json_column) element
        WHERE … -- e.g. element -> 'field' = …
      ) AS filtered_json_column
    FROM
      table
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2014-07-23
      • 2020-03-19
      • 2021-11-13
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多