2016-08-19 108 views
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個元素的人,我需要找到所有元素。有沒有辦法在單個查詢中實現這一點。

謝謝你的時間!

回答

2

您需要使用jsonb_array_elements()函數來獲取數組的所有元素。由於該函數返回一組行,因此需要將其用作行源。

SELECT '1' AS number, 
     jsonb_array_length(data->'people') AS people_count, 
     people->>'firstname' AS FirstName, 
     people->>'lastname' AS LastName, 
     people->'email'->0->>'Address' AS personEmail, 
     people->'phonenumber'->0->>'Number' as personPhone 
FROM listings, jsonb_array_elements(data->'people') p(people) 
WHERE number = '1'; 

這將導致每個人的排在哪一個number = '1'。電子郵件和電話號碼對象也是陣列,我在這裏選擇第一個值。如果你想要所有的JSON數組,你只需要得到整個JSON數組,然後將其包裝在一個外部查詢中,你再次執行jsonb_array_elements()

+0

我想在此查詢中完成的另一件事是針對電話號碼和電子郵件的第0個元素的jsonb_extract_path_text。我試過了jsonb_extract_path_text(people - >'email' - > 0 - >>'Address')以及people - >'email' - > 0 - >> jsonb_extract_path_text('Address')。似乎沒有任何工作..任何想法,如果它是可能的? – phpfreak

+0

函數'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

+0

哦真棒,謝謝! – phpfreak