我在某些表(产品)上有字段,例如“数据”。该字段包含,例如,下一个数据:
[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]
我需要能够找到产品,其中“数据”字段上每个对象数组中的 json 对象包含“文本”:“文本一”或“文本”:“文本二”。通常,我需要进行 IN 查询,但在 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_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
中使用。
关于json - 在 json\jsonb 字段上使用 IN 进行 WHERE 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188297/