【问题标题】:How to insert into table name as alias using pg-promise insert helper?如何使用 pg-promise insert helper 作为别名插入表名?
【发布时间】:2017-11-15 10:13:01
【问题描述】:

这是来自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 上记录我一生的总游戏时间。

更新:简化查询并添加数据结构。

【问题讨论】:

  • 虽然我从参考资料中理解了您的问题,但如果您可以在此处详细说明并提供所有详细信息,那就太好了,因此问题和答案对其他人都有用,而不必去另一个问题。另外,它将帮助搜索索引按关键字定位。
  • 一方面,重要的是展示您的数据模型是什么,以便能够展示如何将数据映射到查询值。我假设您不使用 DateHour 作为属性或其他东西,但我只是猜测。
  • 数据结构可能无关紧要,但我更新了问题中的查询,并添加了数据结构的解释,希望使问题更加关注标题。

标签: node.js postgresql pg-promise


【解决方案1】:

您可以使用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:

【讨论】:

  • 如果没有别名,查询将ERROR: column reference "TimeSpent" is ambiguous。第二种方法更好,细微的区别是我最终只在模板字符串中使用了pgp.helpers.values
  • @woozyking 我已经更新了答案。是的,您可以通过许多不同的方式来解决它,helpers API 最终可以灵活地解决这个问题。我给出的例子就是这样一种方法。
猜你喜欢
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 2020-03-04
  • 2015-11-23
  • 2016-07-14
相关资源
最近更新 更多