2
我想根據匹配鍵獲取jsonb結果。 我有數據庫表「列表」與數字和數據列。postgres + jsonb +從多維數組中獲取密鑰的值
number | data
1 | {"name": "XYZ company", "city": "toronto", "province": "ON", "people" : [
{ "firstName": "tom", "lastName": "hanks",
"phonenumber": [{"type": "mobile", "Number": "111111"}],
"Email": [{"type": "business", "address": "[email protected]"},{"type": "personal", "address": "[email protected]"}] },
{ "firstName": "sandra", "lastName": "petes",
"phonenumber": [{"type": "mobile", "Number": "333"}, {"type": "home", "Number": "444"}],
"Email": [{"type": "business", "address": "[email protected]"}]
}
]}
我需要拉的數據列的所有值的鑰匙 -
- 以人爲>姓
- 以人爲> lastName的
- 以人爲> phonenumber->數
- 人 - >電子郵件 - >地址
我到目前爲止取得的成績是:
SELECT number
,jonb_array_length(jsonb_extract_path(data,'people')) as people_count
,jsonb_extract_path(data,'people','0','firstname') as FirstName
,jsonb_extract_path(data,'people','0','lastname') as LastName
,jsonb_extract_path(data,'people','0','email','Address'") as personEmail
,jsonb_extract_path(data,'people','0','phonenumber','Number') as personPhone
FROM listings
WHERE number='1';
但是,這隻給了我第0個元素的人,我需要找到所有元素。有沒有辦法在單個查詢中實現這一點。
謝謝你的時間!
我想在此查詢中完成的另一件事是針對電話號碼和電子郵件的第0個元素的jsonb_extract_path_text。我試過了jsonb_extract_path_text(people - >'email' - > 0 - >>'Address')以及people - >'email' - > 0 - >> jsonb_extract_path_text('Address')。似乎沒有任何工作..任何想法,如果它是可能的? – phpfreak
函數'jsonb_extract_path()'需要一個'jsonb'參數,後面是一個'text []',因此格式爲'jsonb_extract_path(data,'{people,0,Email,0,address}') '得到「[email protected]」。在上面的解決方案中,「people」數組已經解包,您可以使用'jsonb_extract_path(people,'{Email,0,address}')'獲取所有人的第一個電子郵件地址。 – Patrick
哦真棒,謝謝! – phpfreak