代码之家  ›  专栏  ›  技术社区  ›  Vishal Gajera

Postgres JSONB datatype-如何从Postgres数据库的JSON(JSONB类型)字段中提取数据?

  •  0
  • Vishal Gajera  · 技术社区  · 6 年前

    朋友们好,

    我已经在postgres db表中设置了一组记录,其中表 JSONB 类型字段。

    JSONB公司 JSON ,

    {
      "key1": "value1",
      "key2": "value2",
      "audience": [
        {
          "name": "Person1",
          "email": "test1@mail.com",
          "country": "UK",
          "primaryNumber": "+1234567890",
          "secondaryNumber": "+1234567890"
        },
        {
          "name": "Person2",
          "email": "test2@mail.com",
          "country": "UK",
          "primaryNumber": "+1234567890",
          "secondaryNumber": "+1234567890"
        }
      ]
    }
    

    记录2:-

    {
      "key1": "value1",
      "key2": "value2",
      "audience": [
        {
          "name": "Person3",
          "email": "test3@mail.com",
          "country": "UK",
          "primaryNumber": "+1234567890",
          "secondaryNumber": "+1234567890"
        },
        {
          "name": "Person4",
          "email": "test4@mail.com",
          "country": "UK",
          "primaryNumber": "+1234567890",
          "secondaryNumber": "+1234567890"
        }
      ]
    }
    

    预期结果(获得所有观众):-

    [
      {
        "name": "Person1",
        "email": "test1@mail.com",
        "country": "UK",
        "primaryNumber": "+1234567890",
        "secondaryNumber": "+1234567890"
      },
      {
        "name": "Person2",
        "email": "test2@mail.com",
        "country": "UK",
        "primaryNumber": "+1234567890",
        "secondaryNumber": "+1234567890"
      },
      {
        "name": "Person3",
        "email": "test3@mail.com",
        "country": "UK",
        "primaryNumber": "+1234567890",
        "secondaryNumber": "+1234567890"
      },
      {
        "name": "Person4",
        "email": "test4@mail.com",
        "country": "UK",
        "primaryNumber": "+1234567890",
        "secondaryNumber": "+1234567890"
      }
    ]
    

    帮我设计 一个查询 native query 或通过 spring-data-jpa ?

    我真的很感激如果有人能帮我摆脱这种状况!

    1 回复  |  直到 6 年前
        1
  •  2
  •   klin    6 年前

    你应该提取 'audience' 每行的数组元素 jsonb_array_elements() 并使用 jsonb_agg()

    select jsonb_agg(value)
    from my_table
    cross join jsonb_array_elements(json_data->'audience')
    

    Working example in rextester.