2个数组中具有相同索引的元素的乘积

时间:2017-06-05 03:09:39

标签: sql arrays postgresql unnest

我需要将2个数组的每个元素相乘并投影一个数组,每个元素都是产品结果。

示例:

select * from vetor_query;

返回:

query_id |pesos                                                                                               |
---------|----------------------------------------------------------------------------------------------------|
1        |{2.0000,0.4150,2.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |

查询:

select * from vetor_documento;

返回:

doc    |pesos                                                                                               |
-------|----------------------------------------------------------------------------------------------------|
d1.txt |{3.0000,0.8301,4.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |
d2.txt |{2.0000,0.0000,0.0000,0.0000,2.0000,2.0000,2.0000,2.0000,2.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |
d3.txt |{0.0000,1.0729,0.0000,0.0000,0.0000,0.0000,2.0000,1.0000,0.0000,2.0000,2.0000,0.0000,0.0000,0.0000} |
d4.txt |{0.0000,1.0729,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,5.1699,4.0000,4.0000} |

我需要结合两个查询(交叉连接)并为每个docquery_id生成内部产品的结果数组。

我的第一次尝试就是这个:

select vq.query_id, vd.doc, unnest(vq.pesos) * unnest(vd.pesos)
from vetor_query vq
cross join vetor_documento vd;

然而,它会产生此错误:

  

函数和运算符最多可以使用一个集合参数

1 个答案:

答案 0 :(得分:0)

您可以使用unnest()函数的便捷功能来并行删除多个数组。

LATERAL联接中执行此操作,将每个结果行相乘并将其提供给ARRAY构造函数:

SELECT q.query_id, d.doc, qd.prod
FROM   vetor_query          q
CROSS  JOIN vetor_documento d
CROSS  JOIN LATERAL (
   SELECT ARRAY(SELECT x*y FROM unnest(q.pesos, d.pesos) t(x, y)) AS prod
   ) qd;

这假设所有数组都具有相同的长度,否则剩余元素用NULL填充。

相关:

结果数组中的顺序对应于元素的原始顺序。但请考虑: