从json返回特定值(如果存在),否则返回零行

时间:2018-09-11 11:48:37

标签: json postgresql

我在名为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版。

1 个答案:

答案 0 :(得分:1)

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

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