【问题标题】:results.length is not give the correct output for MySQL query?results.length 没有为 MySQL 查询提供正确的输出?
【发布时间】:2021-04-28 17:22:50
【问题描述】:

为什么 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

请问如何改正?

【问题讨论】:

  • 只返回一个值:count,共 4 个。您希望有多少个 count 值?我们只计算一次而不是 4 次。您想要的实际结果可能类似于console.log(results.total)

标签: javascript mysql sql node.js string-length


【解决方案1】:

results 包含作为数组返回的行。由于您使用的是SELECT COUNT(message),因此您正在查询消息的计数,它返回一行。这一行包含结果,它是一个形状为 { 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!')
}

【讨论】:

    猜你喜欢
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 2020-04-19
    • 2021-10-06
    • 1970-01-01
    • 2011-08-16
    相关资源
    最近更新 更多