获取 json 包含特定对象的记录
Fetch records where json contains a particular object
我有一个 postgres 9.6 table,它有一个 json 字段 config
。我想从此 table 中获取记录,其中 json 具有特定的键值对。
我的table如下
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
知道我哪里出错了。指针将不胜感激。 TIA!!!
运算符@> 仅适用于 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)
在table中使用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)
我有一个 postgres 9.6 table,它有一个 json 字段 config
。我想从此 table 中获取记录,其中 json 具有特定的键值对。
我的table如下
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
知道我哪里出错了。指针将不胜感激。 TIA!!!
运算符@> 仅适用于 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)
在table中使用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)