0

I'm getting [ { 'AVG(Price)': '31000.0000' } ] instead of '31000.0000

this is the function

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;
}

I'm using nodejs mysql2

4

2 回答 2

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
  })
}
于 2017-12-10T20:09:55.860 回答
0
  1. 回调部分是多余的
  2. 这是预期的行为,.query(sql)返回Promise<array of rows>并且 row 是每个键是相应字段名称的对象
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;
}
于 2017-12-13T00:58:48.010 回答