0

我有一个用于插入语句的参数化查询,但我现在想添加一个“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' }

有没有人有任何想法?提前致谢!

4

1 回答 1

0

在做了一些研究之后,我在这里发现了一些有用的东西。我无法让 $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) {...}
于 2015-08-31T19:57:44.993 回答