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

Postgres JSON array contains given array element

我一直在 Whosebug 上搜索这个答案,但没有找到任何有用的东西。 我在 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"}]

我想获取链接->>'ids' 包含 82292 的所有行。因此在这种情况下,它应该 return 我 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' 表达式使用 ->> 运算符将 "[82293,82292]" 检索为字符串(双 > 使其成为 return 文本而不是 jsonb。)内容字符串的转换为数组 ::jsonb.

Example at rextester.com.