Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

sql - How to query nested arrays in a postgres json column?

I have some json similar to the json below stored in a postgres json column. I'm trying query it to identify some incorrectly entered data. I'm basically looking for addresses where the house description is the same as the house number. I can't quite work out how to do it.

{
  "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"
      }
    ]
  }
  ]
}

I have written this sql which will find where the data matches:

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

This obviously only works on the first address on the first school. Is there a way of querying all of the addresses of every school?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use jsonb_array_elements() in lateral join as many times as the depth of a json array which elements you want to compare:

select 
    schools->>'school_id' school_id,
    addresses->>'addr_id' addr_id,
    addresses->>'house_description' house_description,
    addresses->>'house_no' house_no
from title_register_data,
jsonb_array_elements(address_data->'schools') schools,
jsonb_array_elements(schools->'addresses') addresses
where addresses->>'house_description' = addresses->>'house_no';

 school_id | addr_id | house_description | house_no 
-----------+---------+-------------------+----------
 1         | 4       | 1                 | 1
(1 row)  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...