匹配两个数组列 postgresql-9.4-

matching two array columns postgresql-9.4-

在同一行;

Array column 1 has {2,4,5} value  
Array column 2 has {4,8,9} value  

我想做的是查询 table 中匹配上述示例的两个数组列中至少一个数字的行;数字 4 提供此匹配项。

当然,我如何查询 table 中每一行中的每 2 个数组列?我想要 select 行匹配 2 个数组列。

如果安装 intarray 扩展,这就变得很容易,您可以使用 & 运算符来获取两个数组之间的交集:

with data (col1, col2) as (
  values 
    (array[3,4,5], array[4,8,9]), 
    (array[1,2,3,4], array[6,5,1]),
    (array[1,2,3,4], array[7,8,9,10]) 
)
select col1 & col2
from data 
where cardinality(col1 & col2) > 0;

returns:

common_elements
---------------
{4}            
{1}            

编辑

要在没有扩展名或使用 bigint 数组的情况下执行此操作,您可以将两列取消嵌套到集合中,然后对这些集合进行交集。这需要 table(您没有提到)

上的主键(或唯一)列
with data (id, col1, col2) as (
  values 
    (1, array[3,4,5]::bigint[], array[4,8,9]::bigint[]), 
    (2, array[1,2,3,4]::bigint[], array[6,5,1]::bigint[]),
    (3, array[1,2,3,4]::bigint[], array[7,8,9,10]::bigint[]) 
)
select id, array_agg(element) as elements
from (
  select id, unnest(col1) as element
  from data 
  intersect
  select id, unnest(col2)
  from data
) t
group by id;

returns:

id | elements
---+---------
 1 | {4}
 2 | {1}