从 nodejs/pg 中的多个参数更新多行

UPDATE multiple rows from multiple params in nodejs/pg

我将 NodeJS 和 pg 与 PostgreSQL 数据库一起用作后端。 运行 使用 Client.query 的单个查询工作正常。

但是,我遇到了一个挑战,我可以用一种简单而优雅的方式解决它。

我愿意运行:

UPDATE portfolios SET votes =  WHERE id = 

来自 array/list 个:

[{votes: 5, id: 1}, {votes: 15, id: 1}, {votes: 25, id: 2}]

是否可以在单个 Client.query 中完成(或与 pg 类似),这样我就不必制作 "for () { ... }"?

驱动程序必须以这种最终形式将查询传递给 Postgresql:

update portfolios p
set votes = s.votes
from unnest(array[(5, 1), (15, 1), (25, 2)]) s (votes int, id int)
where p.id = s.id

因此将此查询传递给驱动程序:

update portfolios p
set votes = s.votes
from unnest() s (votes int, id int)
where p.id = s.id

使用适当的数组作为参数。

请注意,如果您自己构建它而不是让驱动程序来构建它,您将容易受到 SQL 注入的攻击。