【问题标题】:Node-postgres parameterized query for INSERT INTO if not exists如果不存在,则为 INSERT INTO 的 Node-postgres 参数化查询
【发布时间】:2015-09-01 03:57:44
【问题描述】:

我有一个用于插入语句的参数化查询,但我现在想添加一个“WHERE NOT EXISTS”子句。工作插入看起来像这样:

pgClient.query("INSERT INTO social_posts (username, user_image, message, image_url, post_id, post_url, location, network) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", postArray, 
    function(err, result) {...}

我想实现的是:

pgClient.query("INSERT INTO social_posts(username, user_image, message, image_url, post_id, post_url, location, network) SELECT ($1,$2,$3,$4,$5,$6,$7,$8) WHERE NOT EXISTS (SELECT 1 FROM social_posts WHERE post_id = $9)", postArray,
    function(err, result) {...}

在这种情况下,$9 实际上等于 postArray[4]。

我尝试再次将值推送到数组中,但没有成功:

error running query { [error: operator does not exist: character varying = bigint]
name: 'error',
length: 207,
severity: 'ERROR',
code: '42883',
detail: undefined,
hint: 'No operator matches the given name and argument type(s). You might need to add explicit type casts.',
position: '198',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_oper.c',
line: '722',
routine: 'op_error' }

我尝试插入值,但不起作用:

error running query { [error: there is no parameter $1]
name: 'error',
length: 88,
severity: 'ERROR',
code: '42P02',
detail: undefined,
hint: undefined,
position: '114',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_expr.c',
line: '823',
routine: 'transformParamRef' }

有人有什么想法吗?提前致谢!

【问题讨论】:

  • operator does not exist: character varying = bigint :: 你的参数是一个字符串常量,而 id 是一个整数类型(或相反),但无论哪种方式你都无法比较它们。
  • 它们都是字符串
  • 就这样,PostgreSQL 9.5 终于引入了对 UPSERT 的支持 ;)
  • 感谢@vitaly-t 太棒了!

标签: node.js postgresql node-postgres


【解决方案1】:

在做了一些研究之后,我发现了一些有用的东西 here。我无法让 $9 参数起作用,因为它不能与插值一起使用,这与 SELECT 项周围的一组额外括号有关。正确的语法是:

var postID = postArray[4].toString() // per joop's comment above

pgClient.query("INSERT INTO social_posts(username, user_image, message, image_url, post_id, post_url, location, network) SELECT $1,$2,$3,$4,$5,$6,$7,$8 WHERE NOT EXISTS (SELECT 1 FROM social_posts WHERE post_id = '" + postId + "')", postArray,
function(err, result) {...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多