results.length 没有为 MySQL 查询提供正确的输出?

results.length is not give the correct output for MySQL query?

为什么MySQL查询的结果长度不正确?查询只是计算数据库中 message 列的数量并打印长度。

代码:

connection.query("SELECT COUNT(message) as total FROM `counter`", (err, results) => {
    if(err) throw err;
    console.log(results);
    console.log("the length of result:", results.length);

输出:

[ RowDataPacket { total: 4 } ]
the length of result: 1

正确的长度是 4 而不是 1

请问如何更正?

results 包含作为数组返回的行。由于您使用的是 SELECT COUNT(message),因此您查询的是 returns 一行的消息数。这一行包含结果,它是一个形状为 { total: 4 } 的对象 - 其中 total 来自 SQL 查询的 as total 部分。

要获得实际结果,请检查 results.length > 0 然后您可以访问 results[0].total:

if (results.length > 0) {
  console.log('Total:', results[0].total)
} else {
  throw new Error('No results returned from query!')
}