我一直在 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
转换为数组。
关于postgresql - Postgres JSON 数组包含给定的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42681396/