【问题标题】:Return specific value from json if it exist and zero rows if not如果存在则从 json 返回特定值,如果不存在则返回零行
【发布时间】:2019-02-15 21:58:27
【问题描述】:

我在名为 schema 的列中有这个嵌套的 json 结构:

{"fields" : {"Kommune2015" : {"0101" : "Halden", "0104" : "Moss" }}}

我可以使用:

select schema::jsonb#>>'{fields,Kommune2015,0101}' from meta;
 ?column?
---------
Halden
(1 row)

但如果我查询一个不存在的键,我仍然会得到

select schema::jsonb#>>'{fields,Kommune2015,010}' from meta;
 ?column?

----------
(1 row)

如果键存在,则添加 where 子句将返回一个值:

select schema::jsonb#>>'{fields,Kommune2015,0101}' from meta where schema::jsonb#>>'{fields,Kommune2015,0101}' is not null;

是否可以缩短此查询,以便不必显式命名两次?

这是 10.5 版。

【问题讨论】:

    标签: json postgresql


    【解决方案1】:

    您可以使用子查询或CTE。例如

    with things as (
        select schema::jsonb#>>'{fields,Kommune2015,0101}' thing from meta
    )
    select thing from things where thing is not null
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多