UPDATE multiple rows from multiple params in nodejs/pg

半城伤御伤魂 提交于 2020-01-07 06:40:23

问题


I'm using NodeJS and pg with a PostgreSQL database as backend. Running single queries with Client.query works fine.

However, I've got a challenge which I can solve in a simple and elegant way.

I would like to run:

UPDATE portfolios SET votes = $1 WHERE id = $2

from an array/list of:

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

Can it be done in a single Client.query (or similar with pg), so I don't have to make a "for () { ... }"?


回答1:


The driver must pass the query to Postgresql in this final shape:

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

So pass this query to the driver:

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

with an appropriate array as parameter.

Notice that if you string build it yourself in instead of letting the driver do it you will be vulnerable to SQL injection.



来源:https://stackoverflow.com/questions/37048772/update-multiple-rows-from-multiple-params-in-nodejs-pg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!