首页 > 解决方案 > 如何从 postgres 中正确获取特定键的值。同时删除 null

问题描述

填充数据。

Begin;
    CREATE TEMPORARY TABLE test (id  serial, jdoc jsonb);
    insert into test(jdoc) values('{"a": {"b":"foo"}}');
    insert into test(jdoc) values('{"a": "test"}');
    insert into test(jdoc) values('{"a":[2,3,4]}');
    insert into test(jdoc) values('{"b":[2,3,4]}');
    commit;

基于这个答案, SELECT jsonb_object_agg(key, value) FROM jsonb_each(SELECT (jdoc->'a') from test) WHERE key IN ('a'));但是这个查询不起作用。遇到错误。

 SELECT (jdoc->'a') from test; 

将过滤掉包含键'a'的值。但是这个查询返回 4 行。预计只有 3 行。因为只有 3 行符合条件。那么如何正确地从 postgres 中获取特定键的 jsonb 呢?

标签: postgresqljsonb

解决方案


如果您只想获取包含键的行,请a使用?运算符

select *
from test 
where jdoc ? 'a'

推荐阅读