Pet*_*ter 5 postgresql node.js
正如我已经在 Stackoverflow 上找到的那样,可以通过执行以下操作来更新一个查询中的多行
update test as t set
column_a = c.column_a,
column_c = c.column_c
from (values
('123', 1, '---'),
('345', 2, '+++')
) as c(column_b, column_a, column_c)
where c.column_b = t.column_b;
Run Code Online (Sandbox Code Playgroud)
特别感谢@Roman Pekar 的明确答复。
现在我正在尝试将这种更新方式与查询 NodeJS 中的 postgreSQL 数据库合并。
这是我的代码片段:
var requestData = [
{id: 1, value: 1234}
{id: 2, value: 5678}
{id: 3, value: 91011}
]
client.connect(function (err) {
if (err) throw err;
client.query(buildStatement(requestData), function (err, result) {
if (err) throw err;
res.json(result.rows);
client.end(function (err) {
if (err) throw err;
});
});
});
var buildStatement = function(requestData) {
var params = [];
var chunks = [];
for(var i = 0; i < requestData.length; i++) {
var row = requestData[i];
var valuesClause = [];
params.push(row.id);
valuesClause.push('$' + params.length);
params.push(row.value);
valuesClause.push('$' + params.length);
chunks.push('(' + valuesClause.join(', ') + ')');
}
return {
text: 'UPDATE fit_ratios as f set ratio_budget = c.ratio_budget from (VALUES ' + chunks.join(', ') + ') as c(ratio_label, ratio_budget) WHERE c.ratio_label = f.ratio_label', values: params
}
}
Run Code Online (Sandbox Code Playgroud)
我没有收到错误,但它没有更新我的表,我真的不知道这里出了什么问题。也许我的查询代码中有语法错误?在 NodeJS pg 包中更新时,我只是没有找到多行查询的任何具体示例
vit*_*y-t 12
下面的示例基于库pg-promise及其方法helpers.update:
// library initialization, usually placed in its own module:
const pgp = require('pg-promise')({
capSQL: true // capitalize all generated SQL
});
const db = pgp(/*your connection details*/);
// records to be updated:
const updateData = [
{id: 1, value: 1234},
{id: 2, value: 5678},
{id: 3, value: 91011}
];
// declare your ColumnSet once, and then reuse it:
const cs = new pgp.helpers.ColumnSet(['?id', 'value'], {table: 'fit_ratios'});
// generating the update query where it is needed:
const update = pgp.helpers.update(updateData, cs) + ' WHERE v.id = t.id';
//=> UPDATE "fit_ratios" AS t SET "value"=v."value"
// FROM (VALUES(1,1234),(2,5678),(3,91011))
// AS v("id","value") WHERE v.id = t.id
// executing the query:
await db.none(update);
Run Code Online (Sandbox Code Playgroud)
这种生成多行更新的方法可以表征为:
请注意,我们?在列前面使用id表示该列是条件的一部分,但不会被更新。有关完整的列语法,请参阅类Column和ColumnConfig结构。
相关问题:带有 pg-promise 的多行插入。
| 归档时间: |
|
| 查看次数: |
4962 次 |
| 最近记录: |