我得到了{{' 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
答案 0 :(得分:0)
试试这个:
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
})
}
答案 1 :(得分:0)
1)回调部分是冗余的2)这是预期的行为,.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;
}