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

Product of elements with same index in 2 arrays

我需要将 2 个数组的每个元素相乘并投影一个列,该列是一个数组,每个元素是乘积结果。

示例:

select * from vetor_query;

Returns:

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;

Returns:

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;

但是,它会产生此错误:

Functions and operators can take at most one set argument

您可以使用 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 填充。

相关:

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

  • PostgreSQL unnest() with element number