我在postgres json列中有一些类似于下面的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'
显然,这仅适用于第一所学校的第一地址。有没有办法查询每所学校的所有地址?
jsonb_array_elements()在横向联接中使用的次数与要比较的json数组的深度一样多:
jsonb_array_elements()
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)