我有以下查询:
SELECT prefix FROM username_prefix_pool LEFT JOIN user_creds ON user_creds.prefix_id = username_prefix_pool.id WHERE user_creds.id IN (?);
具有以下参数:
[ 96, 62, 95, 92, 91 ]
我已经通过MySQL工作台测试了此查询,并且确实返回了其中五个结果。
但是,在我的代码(node.js)中,它只返回列表中第一项的结果。
.then((mapListResults) => {
// ^^ results from another query
mapList = mapListResults; // <--- Stores the result
for (let i = 0; i < mapList.length; i++) {
authorIds.push(mapList[i].author_id.toString());
}
console.log('Author IDs');
console.log(authorIds); // this is the [ 96, 62, 95, 92, 91 ]
let searchsql = `SELECT prefix FROM username_prefix_pool LEFT JOIN user_creds ON user_creds.prefix_id = username_prefix_pool.id WHERE user_creds.id IN (?)`;
return new Promise((resolve, reject) => {
connection.query(searchsql, authorIds, (err, rows) => {
if (err) {
console.log(err);
reject(err);
} else {
console.log(rows);
resolve(rows);
}
});
});
})
我曾尝试将数组变成字符串数组,但无济于事。我还尝试过删除SQL语句上的括号(这导致查询错误,因此我将其放回去)。
有什么我想念的吗?
答案 0 :(得分:1)
占位符只是占据列表的第一个元素,因为它认为其余元素有更多的占位符。您应该只提供一个字符串。
您应该更改代码,以便使用以下方式将列表转换为字符串:
console.log('Author IDs');
console.log(authorIds); // this is the [ 96, 62, 95, 92, 91 ]
authorIds=authorIds.join(); // add this line in your code
console.log(authorIds); // you will get a string with 96,62,95,92,91
let searchsql = `SELECT prefix FROM username_prefix_pool LEFT JOIN user_creds ON user_creds.prefix_id = username_prefix_pool.id WHERE user_creds.id IN (?)`;