如何使用pg-promise插入助手将表名称作为别名插入? [英] How to insert into table name as alias using pg-promise insert helper?

查看:104
本文介绍了如何使用pg-promise插入助手将表名称作为别名插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自的后续问题

用例适用于以下查询:

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

Assume the data table contains primary string key on GameName, and an integer column TimeSpent. The purpose let's assume it logs my lifetime total hours of gaming time on given GameName.

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

UPDATE: simplified the query and added the structure of the data.

推荐答案

您可以在 helpers 名称空间以生成您自己的自定义插入内容:

You can use the flexible types in the helpers namespace to generate your own custom insert:

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)
    ]);
}

,然后您只需在其上附加冲突解决子句,因为它是

and then you simply append the conflict-resolution clause to it, since it is static.

示例中使用的API:

  • as.format - used by all query methods to format queries
  • ColumnSet.table - gives you the specialized table object
  • ColumnSet.names - gives you all the columns formatted
  • helpers.values - gives you all the values formatted

这篇关于如何使用pg-promise插入助手将表名称作为别名插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆