简体   繁体   English

如何在Postgres中查询数组存储列,(数组交集)

[英]How to query array stored column in Postgres, (array intersection)

I have a table which contains value in array something like this. 我有一个表格,其中包含类似这样的数组值。

id | contents_id
 1 | [1, 3, 5]
 2 | [1, 2]
 3 | [3, 4, 6]
 4 | [2, 5]

How to write a query array eg [1, 2] such that it check value of array not array as a whole ? 如何编写查询数组,例如[1, 2] ,以便它检查数组的值不是整个数组?

If any common value of array is found get all tuples. 如果找到任何常见的数组值,则获取所有元组。

If [1, 2] is queried it must fetch id => 1, 2, 4 from above table as it contains 1 or 2 . 如果查询[1, 2] ,它必须从上表中获取id => 1, 2, 4 ,因为它包含12

Consider using the intarray extension. 考虑使用intarray扩展。 It provides a && operator for testing integer array overlapping. 它提供了一个用于测试整数数组重叠的&&运算符。 Here is a fiddle, with an example. 是一个小提琴,举个例子。

select id from test where ARRAY[1,2] && contents_id;

Though you can query it with the operator, I think it will be better to make a junction table with integer IDs. 虽然您可以使用运算符查询它,但我认为最好使用整数ID创建联结表。

On 1-D int arrays && operator arrayoverlap is the fastest as @LaposhasúAcsa suggested. 在@LaposhasúAcsa建议的1-D int数组&&运算符arrayoverlap是最快的。

so my answer stands only if arrayoverlap is not avaliable or want to work with anything other than one dimensional integer arrays. 所以我的答案只有在arrayoverlap不可用或想要使用除一维整数数组以外的任何东西时才会有效。

Check UNNEST https://www.postgresql.org/docs/current/static/functions-array.html 检查UNNEST https://www.postgresql.org/docs/current/static/functions-array.html

CREATE TABLE t45407507 (
   id SERIAL PRIMARY KEY 
  ,c int[]
);
insert into t45407507 ( c) values
    (ARRAY[1,3,5])
  , (ARRAY[1,2])
  , (ARRAY[3,4,6])
  , (ARRAY[2,5]);

select DISTINCT id from 
  (SELECT id,unnest(c) as c
  from t45407507) x 
where x.c in (1,2);

Can be shortened with LATERAL join 可以通过LATERAL加入缩短

select DISTINCT id from
   t45407507 x,unnest(c) ec
where ec in (1,2);

The comma (,) in the FROM clause is short notation for CROSS JOIN . FROM子句中的逗号(,)是CROSS JOIN简短表示法。 LATERAL is assumed automatically for table functions like unnest() . 自动假设LATERAL用于表函数,例如unnest()

Rewrite WHERE to use ARRAY as parameter 重写WHERE以使用ARRAY作为参数

SELECT DISTINCT id FROM
  t45407507 x,unnest(c) ec
WHERE ec = ANY(ARRAY[1,2]);

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

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