【问题标题】:Only extract json if field not null如果字段不为空,则仅提取 json
【发布时间】:2021-02-23 06:10:56
【问题描述】:

我想从(可为空的)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"

如何实现上述输出?

【问题讨论】:

    标签: sql arrays json postgresql lateral-join


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 1970-01-01
      • 2017-11-18
      • 2020-09-15
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多