1

我正在style text[]使用 contains 运算符查询数组列 () @>。我的原始查询是:

SELECT * FROM songs WHERE style @> '{Acoustic}'

当我将它放入节点(使用pg-pool)并尝试对其进行参数化时,值引用周围的大括号似乎阻止它正常工作。请注意以下示例:

const style = 'Acoustic';

// this works, but I don't want to in-line like this:
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{` + style + `}'`);

// this fails with 'error: bind message supplies 1 parameters, but prepared statement "" requires 0'
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{$1}'`, [style]);

参数化这个的正确方法是什么?

4

1 回答 1

2
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{$1}'`, [style]);

此处的 $1 用引号引起来,仅被视为字符串的一部分,而不是可替换的变量。如果您希望传入一个标量并将其视为一个数组,您应该可以这样做:

const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> ARRAY[$1]`, [style]);

另一种方法可能是让 node.js 直接绑定一个数组(未测试):

const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> $1`, [[style]]);
于 2020-07-30T14:38:47.577 回答