在json \ jsonb字段上使用IN进行查询 [英] WHERE query with IN on json\jsonb field
本文介绍了在json \ jsonb字段上使用IN进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在某些表(产品)上有字段,例如数据".例如,此字段包含下一个数据:
I have field on some table (products), like "data". This field contains, for example, next data:
[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]
我需要能够找到产品,其中数据"字段上每个对象数组内的json对象包含文本":文本一"或文本":文本二".通常,我需要进行IN查询,但是要在json数据"字段中->数组->对象.
I need to be able find products, where json objects inside each object array on "data" field contain "text" : "Text one" or "text" : "Text two". Generally, I need to do IN query, but inside json "data" field -> array -> object.
推荐答案
示例数据:
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_array_elements()
:
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)
注意:data
必须转换为jsonb
才能在distinct
中使用.
Note: data
must be cast to jsonb
to be used in distinct
.
这篇关于在json \ jsonb字段上使用IN进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文