执行'SELECT COUNT'查询后,无法从RowDataPacket访问'COUNT(id)'

时间:2019-06-20 10:38:34

标签: javascript mysql node.js

我想访问包含计数元素实际数量的变量,但我不知道如何。

    sql = "SELECT COUNT(id) FROM users WHERE username='" + req.body.username + "' AND password='" + req.body.password + "';";
    con.query(sql, function (err, result) {
    if (err) throw err;
    })

result是:[ RowDataPacket { 'COUNT(id)': 0 } ];我无法使用语法result.COUNT(id)访问数据,因为出现错误:ReferenceError: id is not defined

2 个答案:

答案 0 :(得分:1)

count使用别名,为了更好地抽象,请在查询中使用模板文字

 sql = `SELECT COUNT(id) as count FROM users WHERE username=${req.body.username}  AND password=${req.body.password}`;
    con.query(sql, function (err, result) {
        if (err) throw err;
    })
  

对于[RowDataPacket {'total':0}],请尝试

     sql = `SELECT COUNT(id) as count FROM users WHERE username=${req.body.username}  AND password=${req.body.password}`;
            con.query(sql, function (err, result) {
                if (err) throw err;
                  else{
let results=JSON.parse(JSON.stringify(result)) // gives you an js object array
    } })

答案 1 :(得分:0)

给您的字段一个别名(标签)

sql = "SELECT COUNT(id) as total FROM users WHERE username='" + req.body.username + "' AND password='" + req.body.password + "';";

结果将为[ RowDataPacket { 'total': 0 } ]