【问题标题】:Fetch records where json contains a particular object获取 json 包含特定对象的记录
【发布时间】:2020-08-06 08:01:38
【问题描述】:

我有一个 postgres 9.6 表,其中有一个 json 字段 config。我想从此表中获取 json 具有特定键值对的记录。

我的表如下

CREATE TABLE features(
    id integer NOT NULL,
    plan character,
    config json NOT NULL
)

在json字段中,我在表单中存储了一个json

[
    { "name": "A", "state": "active"},
    { "name": "B", "state": "inactive"},
    { "name": "C", "state": "active"}
]

现在,我正在查询数据库以获取 json 字段包含键值对 { "name": "B", "state": "inactive"} 的所有记录。

我的查询如下

select * from features where config @> '[{ "name": "B", "state": "inactive"}]';

但是,我得到一个错误

ERROR:  operator does not exist: config @> unknown

知道我在哪里出错了。指针将不胜感激。蒂亚!!!

【问题讨论】:

    标签: postgresql postgres-9.6


    【解决方案1】:

    运算符@>仅适用于jsonb数据类型:

    CREATE TABLE features(
        id integer NOT NULL,
        plan character,
        config jsonb NOT NULL
    );
    CREATE 
    
    insert into features values(1,'a',' [ { "name": "A", "state": "active"}, { "name": "B", "state": "inactive"}, { "name": "C", "state": "active"} ]');
    INSERT 0 1
    
    select * from features where  config @> '[{ "name": "B", "state": "inactive"}]';
     id | plan |                                                  config                                                  
    ----+------+----------------------------------------------------------------------------------------------------------
      1 | a    | [{"name": "A", "state": "active"}, {"name": "B", "state": "inactive"}, {"name": "C", "state": "active"}]
    (1 row)
    

    表中有json数据类型,可以使用:

    select * from 
     (select json_array_elements(config)::jsonb  as item from features) as setofjsonb
    where item = '{"name": "B", "state": "inactive"}'::jsonb;
                    item                
    ------------------------------------
     {"name": "B", "state": "inactive"}
    (1 row)
    

    【讨论】:

    • 感谢您的回答,但如果您能给我一个 json 数据类型的解决方案会很有帮助,因为我无法更改现有的表结构。
    • 我已经为json日期类型添加了一个解决方案,但我认为您需要在查询期间转换为jsonb,否则您只能转换为对json不太可靠的文本。
    • @ChaitanyaWaikar:直接投吧where config::jsonb @> ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2021-12-31
    • 2014-04-28
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多