在 json\jsonb 字段上使用 IN 进行 WHERE 查询
WHERE query with IN on json\jsonb field
我在某些 table(产品)上有字段,例如 "data"。例如,该字段包含下一个数据:
[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]
我需要能够找到产品,其中 "data" 字段上每个对象数组中的 json 个对象包含 "text" : "Text one" 或 "text" : "Text two"。一般需要IN查询,但是在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
中使用。
我在某些 table(产品)上有字段,例如 "data"。例如,该字段包含下一个数据:
[{"text" : "Text one"}, {"text" : "Text two"}, {"text" : "Text three"}]
我需要能够找到产品,其中 "data" 字段上每个对象数组中的 json 个对象包含 "text" : "Text one" 或 "text" : "Text two"。一般需要IN查询,但是在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
中使用。