我正在尝试根据匹配键获取jsonb结果。 我有DB表“listing”,包含数字和数据列。
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个元素,我需要找到所有元素。有没有办法在单个查询中实现这一点。
谢谢你的时间!
答案 0 :(得分:3)
您需要使用self
函数来获取数组的所有元素。由于该函数返回一组行,因此您需要将其用作行源。
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';
的每个人都排成一行。电子邮件和电话号码对象也是数组,我在这里只选择第一个值。如果你想要所有这些,你只需要获取整个JSON数组,然后将它包装在外部查询中再次number = '1'
。