仅当字段不为空时提取json

时间:2020-11-11 09:17:54

标签: sql arrays json postgresql lateral-join

我想从(空)JSONB字段中提取键值。如果该字段为NULL,则我希望该记录仍存在于我的结果集中,但字段为空。

customer表:

id, name, phone_num, address
1, "john", 983, [ {"street":"23, johnson ave", "city":"Los Angeles", "state":"California", "current":true}, {"street":"12, marigold drive", "city":"Davis", "state":"California", "current":false}]
2, "jane", 9389, null
3, "sally", 352, [ "street":"90, park ave", "city":"Los Angeles", "state":"California", "current":true} ]

当前PostgreSQL查询:

select id, name, phone_num, items.city
from customer, 
     jsonb_to_recordset(customer) as items(city str, current bool)
where items.current=true

它返回:

id, name, phone_num, city
1, "john", 983, "Los Angeles"
3, "sally", 352, "Los Angeles"

必需的输出:

id, name, phone_num, city
1, "john", 983, "Los Angeles"
2, "jane", 9389, null
3, "sally", 352, "Los Angeles"

如何实现以上输出?

1 个答案:

答案 0 :(得分:1)

使用left join lateral代替隐式横向联接:

select c.id, c.name, c.phone_num, i.city
from customer c
left join lateral jsonb_to_recordset(c.address) as i(city str, current bool)
    on i.current=true