简体   繁体   English

如何查询 jsonb 数组以查找它是否包含查询列表中的值?

[英]How can I query a jsonb array to find if it contains a value from a query list?

Currently my table looks something like this目前我的桌子看起来像这样

 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"}]}

I want to grab all the rows were the companies JSONB array contains a company with industry in a the list ["TECH", "SPORTS"] .如果companies JSONB 数组在列表["TECH", "SPORTS"]中包含具有行业的公司,我想获取所有行。

In this example, the query would return rows 1 and 3.在此示例中,查询将返回第 1 行和第 3 行。

I'm unsure of how to do this due to the nesting involved.由于涉及嵌套,我不确定如何执行此操作。

You can use jsonb_array_elements() and exists :您可以使用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')
)

Another way to write this, is to use the contains operator @>另一种写法是使用包含运算符@>

select *
from the_table t
where t.companies -> 'companies' @> '[{"industry": "TECH"}]'
   or t.companies -> 'companies' @> '[{"industry": "SPORTS"}]'

This could make use of a GIN index on companies这可以利用companies的 GIN 指数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM