为什么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。
请问如何纠正这个问题?
发布于 2021-01-25 04:46:04
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!')
}https://stackoverflow.com/questions/65875718
复制相似问题