Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何查询jsonb数组以查找它是否包含查询列表中的值?_Sql_Arrays_Postgresql_Jsonb_Postgresql 9.5 - Fatal编程技术网

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

Sql 如何查询jsonb数组以查找它是否包含查询列表中的值?,sql,arrays,postgresql,jsonb,postgresql-9.5,Sql,Arrays,Postgresql,Jsonb,Postgresql 9.5,目前我的桌子看起来像这样 id | companies ----+------------------------------------------------------------------- 1 | {"companies": [{"name": "Google", "industry": "TECH"},

目前我的桌子看起来像这样

 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"}]}
我想抓取所有的行都是
公司
JSONB数组包含一个行业在列表中的公司
[“TECH”,“SPORTS”]

在本例中,查询将返回第1行和第3行


由于涉及嵌套,我不确定如何执行此操作。

您可以使用
jsonb\u array\u 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')
)

另一种编写方法是使用contains操作符
@>

select *
from the_table t
where t.companies -> 'companies' @> '[{"industry": "TECH"}]'
   or t.companies -> 'companies' @> '[{"industry": "SPORTS"}]'
这可以利用
公司上的GIN索引

谢谢:)我在发布后玩了
jsonb\u array\u elements()
,但看起来我使用了不正确的语法作为输入!