在我的NodeJS应用程序中使用pg
,我希望能够将数组传递给函数,以便可以将IN
语句用作查询的一部分
示例
async function myMethod(array) {
// array looks like [ '83', '82', '54', '55', '79' ] for example
let response;
try {
response = await pool.query("SELECT * FROM fixtures WHERE id IN($1)", [array]);
} catch (e) {
console.log(e);
}
return response.rows;
}
我遇到错误
{ error: invalid input syntax for integer: "{"83","82","54","55","79"}"
请问如何在这里构建查询结构?
答案 0 :(得分:3)
您最好的选择是:
private var sectionIndices: [String] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
for beginningLetter in self.sectionIndices {
print("Finding artists for \(beginningLetter)")
let artists: Results<Artist>
if beginningLetter == "#" {
artists = self.artists.filter(startsWithNumberPredicate, self.sectionIndices)
} else {
artists = self.artists.filter("name BEGINSWITH[cd] %@", beginningLetter).sorted(byKeyPath: "name", ascending: true)
}
}
当变量以pool.query("SELECT * FROM fixtures WHERE id IN($1:list)", [array]);
// [1,2,3]→"SELECT * FROM fixtures WHERE id IN(1,2,3)"
结尾时,其格式设置为逗号分隔值的列表,每个值的格式均取决于其JavaScript类型。
您需要这样做的原因是,默认情况下将数组格式化为PostgreSQL数组,这就像用花括号表示的那样。
注意:此内容已在v7.5.1中添加到:list
(或更确切地说,pg
)中。如果您使用的是早期版本,请改用pg-promise
。