其中,在json\jsonb字段上使用IN进行查询
我在一些表(产品)上有字段,如“数据”。例如,此字段包含下一个数据:其中,在json\jsonb字段上使用IN进行查询,json,postgresql,jsonb,Json,Postgresql,Jsonb,我在一些表(产品)上有字段,如“数据”。例如,此字段包含下一个数据: [{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}] 我需要能够找到产品,其中“数据”字段中每个对象数组中的json对象包含“文本”:“文本一”或“文本”:“文本二”。通常,我需要在查询中执行,但在json“数据”字段->数组->对象中。示例数据: create table products(id int, data json); in
[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]
我需要能够找到产品,其中“数据”字段中每个对象数组中的json对象包含“文本”:“文本一”或“文本”:“文本二”。通常,我需要在查询中执行,但在json“数据”字段->数组->对象中。示例数据:
create table products(id int, data json);
insert into products values
(1, '[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]'),
(2, '[{"text" : "Text four"}, {"text" : "Text two"}, {"text" : "Text three"}]');
使用json\u array\u elements()
:
注意:data
必须强制转换为jsonb
才能在distinct
中使用
select distinct id, data::jsonb
from (
select *
from products p,
json_array_elements(data)
) s
where value->>'text' in ('Text one', 'Text two')
order by id;
id | data
----+-----------------------------------------------------------------------
1 | [{"text": "Text one"}, {"text": "Text two"}, {"text": "Text three"}]
2 | [{"text": "Text four"}, {"text": "Text two"}, {"text": "Text three"}]
(2 rows)