postgresql - Postgres JSON 数组包含给定的数组元素

标签 postgresql jsonb

我一直在 stackoverflow 上寻找这个答案,但没有找到任何有用的东西。 我在 my_tbl 中的数据为:

folder_id |  links                                                                                                     
--------------+----------------------------------------------------------------
   761 | [{"ids": "[82293,82292]", "index": "index_1"}, {"ids": "[82293,82292]", "index": "index_2"}]
   769 | [{"ids": "[82323,82324]", "index": "index_3"}]
   572 | [{"ids": "[80031,79674,78971]", "index": "index_4"}]
   785 | [{"ids": "[82367,82369]", "index": "index_5"}, {"ids": "[82368,82371]", "index": "index_6"}]
   768 | [{"ids": "[82292,82306]", "index": "index_7"}]

我想获取 links->>'ids' 包含 82292 的所有行。所以在这种情况下,它应该返回 folder_id 761 和 768。

到目前为止,我实现的是通过 - 将 ids 数组与链接分开 jsonb_array_elements(链接) ->> 'ids'

不确定如何进一步进行。

最佳答案

您可以使用 jsonb_array_elements 将 json 数组转换为行集。您可以将其用于“ids”的值。使用the @> operator您可以检查数组是否包含一个值:

select  distinct folder_id
from    YourTable
cross join lateral
        jsonb_array_elements(links) ids(ele)      
where   (ele->>'ids')::jsonb @> '[82292]'

一个棘手的部分是 [82293,82292]" 存储为字符串,而不是数组。 ele->>'ids' 表达式使用 ->> 运算符(双 > 使它返回文本而不是 jsonb。)字符串的内容由 ::jsonb 转换为数组。

Example at rextester.com.

关于postgresql - Postgres JSON 数组包含给定的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42681396/

相关文章:

postgresql - 如何正确制作在 Golang 中与 go 有很多关联

mysql - PG::UndefinedTable: 错误:关系 'caves' 不存在

PostgreSQL - 将键添加到 JSONB 数组的每个对象

postgresql - 修改 postgres 中的 JSONB 字段

sql - Postgres JSONB 从数据数组中进行选择

json - Postgresql更新json数据属性

Django 使用不正确的序列起始值为 Postgresql 创建测试数据库

postgresql - 在复杂查询上生成有序序列排名

c - 读取 SELECT 的值并将其作为 int 存储在 C 中

json - 使用 PostgreSQL 和 JSONB 选择 "WHERE IN"