2017-05-19 93 views
2

我有一些json類似於下面的json存儲在postgres json列中。我試圖查詢它來識別一些錯誤輸入的數據。我基本上在尋找房子描述與房屋編號相同的地址。我無法弄清楚如何去做。如何查詢postgres 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' 

這顯然只適用於第一個學校的第一個地址。有沒有辦法查詢每所學校的所有地址?

回答

4

使用jsonb_array_elements()橫向加入多次,要比較的元素JSON數組的深度:

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) 
+0

優秀謝謝你。那就是我所追求的。我做了微調,並使用了json_array_elements,因爲它不是jsonb列,但原理相同。 – spannerj