如何在postgres json列中查询嵌套数组?

时间:2017-05-19 17:11:18

标签: sql arrays json postgresql nested

我有一些json类似于下面存储在postgres json列中的json。我正在尝试查询它以识别一些错误输入的数据。我基本上都在寻找房屋描述与房屋号码相同的地址。我无法理解如何做到这一点。

{
  "timestamp": "2014-10-23T16:15:28+01:00",
  "schools": [
    {
    "school_id": "1",
    "addresses": [
      {
        "town": "Birmingham",
        "house_description": "1",
        "street_name": "Parklands",
        "addr_id": "4",
        "postcode": "B5 8KL",
        "house_no": "1",
        "address_type": "UK"
      },
      {
        "town": "Plymouth",
        "house_description": "Flat a",
        "street_name": "Fore Street",
        "addr_id": "2",
        "postcode": "PL9 8AY",
        "house_no": "15",
        "address_type": "UK"
      }
    ]
  },
  {
    "school_id": "2",
    "addresses": [
      {
        "town": "Coventry",
        "street_name": "Shipley Way",
        "addr_id": "19",
        "postcode": "CV8 3DL",
        "house_no": "662",
        "address_type": "UK"
      }
    ]
  }
  ]
}

我写了这个sql,它将找到数据匹配的位置:

select *
FROM title_register_data
where address_data->'schools'->0->'addresses'->0->>'house_description'= 
address_data->'schools'->0->'addresses'->0->>'house_no'

这显然只适用于第一所学校的第一个地址。有没有办法查询每所学校的所有地址?

1 个答案:

答案 0 :(得分:16)

在横向连接中使用SELECT FLOOR(EXTRACT(EPOCH FROM (now() - updated_at))/60) :: INT as minutes_since_update FROM table_a WHERE column_a IS TRUE AND column_b IS NULL AND CURRENT_TIME BETWEEN '00:00:00' AND '07:00:00' LIMIT 1; 的次数与要比较的元素的json数组的深度相同:

jsonb_array_elements()