json - 在 json\jsonb 字段上使用 IN 进行 WHERE 查询

标签 json postgresql jsonb

我在某些表(产品)上有字段,例如“数据”。该字段包含,例如,下一个数据:

[{"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/

相关文章:

javascript - 如何使用 Javascript 触发 Pusher 事件

javascript - 使用 json 从数据库检索纬度经度到 php 页面

json - 将 json 响应转换为字符串并将其放入结构中

PostgreSQL 删除重复项

knex.js - 使用 knex 从 postgresql jsonb 检索特定 key

json - 如何通过 jsonḃ postgres 求和列组

json - java.lang.NoClassDefFoundError 当已经将 jar 文件导入到 android studio 时

sql - 在 PostgreSQL 中选择子数组及其长度

postgresql - Postgres 在创建查询计划时不使用 HASH 索引

ruby-on-rails - 为 jsonb 值搜索构建 Activerecord/SQL 查询