I’m using felixge’s node-mysql plugin for Node.js. I want to find the highest ID in my database, so I use:
client.query(
"SELECT MAX('hits_total') FROM " + TABLE,
function (err, results, fields) {
if(err) {
throw err;
}
console.log(results);
console.log(fields);
}
);
But how do I find the value of the result? The console logs:
{ 'MAX(\'hits_total\')':
{ length: 39,
received: 39,
number: 2,
type: 4,
catalog: 'def',
name: 'MAX(\'hits_total\')',
charsetNumber: 192,
fieldLength: 30,
fieldType: 253,
flags: 0,
decimals: 31 } }
{"MAX('hits_total')":"hits_total"}
So I get one result, however I can not find it’s value (which is 633 in this case).
If anyone can help me or point me in the right direction, that would be great 😀
edit
Ok, so I’ve done some more testing and it seems that there is something wrong with the syntax "SELECT MAX('hits_total') FROM " + TABLE,
I can tell because when I change it to, for instance:
"SELECT * FROM " + TABLE + " WHERE id=200"
it suddenly returns a valid object:
{ id: 200, hits_total: 102 }
So maybe MAX(‘whatever_field’) isn’t supported yet? How can I find out, and are there alternatives to achieve the same effect?
another edit > I can’t answer my own question within 8 hours, so here it is:
Right, I’ve found a solution.
Like mentioned, the syntax ("SELECT MAX('hits_total') FROM " + TABLE for some reason doesn’t return a useful object.
So instead, I use this syntax (I’ll paste the entire block for completeness):
var hits = 0;
var query = client.query("SELECT * FROM hits ORDER BY hits_total DESC LIMIT 1");
query
.on('row', function(row) {
console.log("(row)");
hits = row.hits_total;
})
.on('end', function(result) {
console.log("(end)");
});
The row object returned by query.on('row', callback(row){}); has the fieldname(s) of that row as properties – in this case .hits_total.
resultsshould be an array if it is actually returning the rows. In this case it looks like it is returning something else instead.The issue is with your query, not with your code. You have single-quotes around “hits_total”, so it is literally taking the maximum of a string. Remove the single quotes, or change them to back-ticks, and then it will process the string as a column name.