【问题标题】:MySQL IN returning only the results of the first item in the arrayMySQL IN 只返回数组中第一项的结果
【发布时间】:2020-01-13 06:24:31
【问题描述】:

我有以下疑问:

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 语句上的括号(导致查询错误,所以我把它放回去了)。

我有什么遗漏吗?

【问题讨论】:

  • 这是因为你在 authorIds 中给出了一个列表。你应该给出一个包含所有元素的字符串

标签: javascript mysql


【解决方案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 (?)`;

【讨论】:

  • 奇怪,这表示我可以传递一个数组:stackoverflow.com/questions/46535318/… 无论如何,不​​幸的是它没有工作。我仍然只能获得 ID 96 的详细信息。
  • 是的,但是要使用列表,您应该为列表的每个元素指定一个占位符,如下所示: 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 (?,?,?,?,?)";
  • 我不知道为什么您的初始代码不起作用(这似乎合乎逻辑),但那个代码就起作用了!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 2014-04-17
  • 2016-05-23
  • 1970-01-01
  • 2014-09-25
  • 2013-11-15
相关资源
最近更新 更多