[英]How can I query a jsonb array to find if it contains a value from a query list?
目前我的桌子看起來像這樣
id | companies
----+-------------------------------------------------------------------
1 | {"companies": [{"name": "Google", "industry": "TECH"},
| {"name": "FOX News", "industry": "MEDIA"}]}
----+--------------------------------------------------------------------
2 | {"companies": [{"name": "Honda", "industry": "AUTO"}]}
----+--------------------------------------------------------------------
3 | {"companies": [{"name": "Nike", "industry": "SPORTS"}]}
如果companies
JSONB 數組在列表["TECH", "SPORTS"]
中包含具有行業的公司,我想獲取所有行。
在此示例中,查詢將返回第 1 行和第 3 行。
由於涉及嵌套,我不確定如何執行此操作。
您可以使用jsonb_array_elements()
並exists
:
select t.*
from mytable t
where exists (
select 1
from jsonb_array_elements(t.companies -> 'companies') x(obj)
where x.obj ->> 'industry' in ('TECH', 'SPORTS')
)
另一種寫法是使用包含運算符@>
select *
from the_table t
where t.companies -> 'companies' @> '[{"industry": "TECH"}]'
or t.companies -> 'companies' @> '[{"industry": "SPORTS"}]'
這可以利用companies
的 GIN 指數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.