WHERE query with IN on json\jsonb field

北战南征 提交于 2019-12-11 12:40:43

问题


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"}]

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.


回答1:


Example data:

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"}]');

Use 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)

Note: data must be cast to jsonb to be used in distinct.



来源:https://stackoverflow.com/questions/34188297/where-query-with-in-on-json-jsonb-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!