看来 postgres 本身就支持使用运算符进行数组追加:
|| array-to-array concatenation ARRAY[1,2,3] || ARRAY[4,5,6] {1,2,3,4,5,6}
来源:https://www.postgresql.org/docs/current/functions-array.html .
它本身是否支持向量/元素算术运算(即,无需为其编写新函数?)
例如,类似:
[1,2,3] + [1,1,1] = [2,3,4]
[1,2,3] - [1,1,1] = [0,1,2]
[1,2,3] * [2,2,2] = [2,4,6]
[1,2,3] / [2,2,2] = [.5, 1, 1.5]
相关问题在这里:Vector (array) addition in Postgres ,虽然它已经有大约 6 年的历史了,所以也许从那时起 postgres 已经发生了变化?
最佳答案
Postgres 没有支持此类算术的“数字数组”概念。然而,使用数组原语实现起来很容易。例如:
select t.*,
(select array_agg(e.el1 * e.el2)
from unnest(t.ar1, t.ar2) e(el1, el2)
) ar
from (select array[1,2,3] as ar1, array[4,5,6] as ar2) t;
unnest()
按元素顺序“解压缩”两个数组。然后数组 agg 根据您想要的数学运算“重新压缩”它们。
实际上,Postgres 确实通过子查询保留了数组的顺序。但如果你想明确一点,请使用withordinality
:
select t.*,
(select array_agg(e.el1 * e.el2 order by n)
from unnest(t.ar1, t.ar2) with ordinality e(el1, el2, n)
) ar
from (select array[1, 2, 3] as ar1, array[4, 5, 6] as ar2) t
关于sql - postgres 中数组的向量算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65471274/