node.js - 如何使用 pg-promise 插入助手将表名作为别名插入?

标签 node.js postgresql pg-promise

这是此 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:

关于node.js - 如何使用 pg-promise 插入助手将表名作为别名插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524779/

相关文章:

node.js - 使用 express-jwt 作为中间件来验证 Azure AD 颁发的 token

javascript - 与域在同一台计算机上运行的 NODEJS 服务器的 CORS 错误

ruby-on-rails - Rails 搜索索引 : Sphinx or Solr?

pg-promise - 为什么我们应该使用batch()而不是Promise.all?

javascript - 在 pg-promise 中使用助手时如何设置列

javascript - 来自 API 的 node.js pg-promise 和分页

node.js - Visual Studio 2013 可以在 Node Js Web 应用程序中调试客户端 JavaScript

javascript - npm 异步模块不执行最终回调

sql - 可写公用表表达式和多个插入语句

python-3.x - 值错误 :unsupported format character 'd' (0x64) at index %Id