为什么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)
,因此查询的是返回一行的消息计数。这一行包含结果,它是形状为{ 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!')
}