这是此 comment 的后续问题
用例适用于以下查询:
INSERT INTO "GamingLogs" AS GL ("GameName", "TimeSpent")
VALUES ('LOL', '2'),
('DOTA2', '1'),
('Mobius Final Fantasy', '3')
ON CONFLICT ("GameName") DO UPDATE
SET "TimeSpent" = GL."TimeSpent" + EXCLUDED."TimeSpent"
假设数据表包含 GameName
上的主字符串键和一个整数列 TimeSpent
。我们假设它的目的是记录我一生中在给定 GameName
上玩游戏的总小时数。
更新:简化了查询并添加了数据结构。
最佳答案
您可以在 helpers 中使用灵活的类型命名空间以生成您自己的自定义插入:
const pgp = require('pg-promise')(/*initialization options*/);
// data = either one object or an array of objects;
// cs = your ColumnSet object, with table name specified
// alias = the alias name string
function createInsertWithAlias(data, cs, alias) {
return pgp.as.format('INSERT INTO $1 AS $2~ ($3^) VALUES $4^', [
cs.table, alias, cs.names, pgp.helpers.values(data, cs)
]);
}
然后您只需将冲突解决子句附加到它,因为它是静态的。
示例中使用的API:
- as.format - 所有查询方法都使用它来格式化查询
- ColumnSet.table - 为您提供专门的表格对象
- ColumnSet.names - 为您提供所有格式化的列
- helpers.values - 为您提供所有格式化的值
关于node.js - 如何使用 pg-promise 插入助手将表名作为别名插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524779/