我正在得到[{'avg(price)':'31000.0000'}],而不是'31000.0000
这是功能
async function getAveragePrice(year) {
const sql = await init();
const [rows] = await sql.query('SELECT AVG(Price) FROM Car where year=
?', [year], (err, result) => {
if (err) {
return null;
}
});
return rows;
}
我正在使用nodejs mysql2
- 回调部分是冗余
- 这是预期的行为,
.query(sql)
返回Promise<array of rows>
,行是每个键是相应的字段名称
的对象
async function getAveragePrice(year) {
const db = await init();
const [rows] = await db.query('SELECT AVG(Price) as avg FROM Car where year=?', [year])
return rows[0].avg;
}
尝试以下:
async function getAveragePrice(year) {
const sql = await init()
const row = await sql.query('SELECT AVG(Price) AS avg_price FROM Car where year=?', year, (err, result) => {
if (err) {
return null
}
return result.avg_price
})
}