1

我有一个带有 json 字段的 postgres 9.6 表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

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

4

1 回答 1

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)
于 2020-04-23T06:59:21.917 回答