postgres + jsonb + 从多维数组中获取键值

postgres + jsonb + get values of key from multidimentional array

我正在尝试根据匹配键获取 jsonb 结果。 我有带有数字和数据列的 DB table "listings"。

    number | data  
      1    |  {"name": "XYZ company", "city": "toronto", "province": "ON", "people" : [
{ "firstName": "tom", "lastName": "hanks", 
   "phonenumber": [{"type": "mobile", "Number": "111111"}], 
    "Email": [{"type": "business", "address": "tom@xyz.com"},{"type": "personal", "address": "tom@mailinator.com"}] }, 

{ "firstName": "sandra", "lastName": "petes", 
   "phonenumber": [{"type": "mobile", "Number": "333"}, {"type": "home", "Number": "444"}], 
    "Email": [{"type": "business", "address": "sandra@xyz.com"}] 
}
]}

我需要使用键提取数据列的所有值 -

目前我取得的成绩是:

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 个元素的人,我需要找到所有元素。有没有办法在单个查询中实现这一点。

感谢您的宝贵时间!

您需要使用jsonb_array_elements() 函数来获取数组的所有元素。由于该函数 returns 一组行,因此您需要将其用作行源。

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' 处的每个人生成一行。电子邮件和 phone 数字对象也是数组,我在这里只选择第一个值。如果你想要所有这些,你只需要获取整个 JSON 数组,然后将其包装在你再次执行 jsonb_array_elements() 的外部查询中。