What I want to do is SUM a column, but also COUNT the number of rows it is summing, with a limit of no more than 5 rows. So my query is:
SELECT COUNT(*), SUM(score) FROM answers WHERE user=1 LIMIT 5
What I expected back was a COUNT(*) up to 5 (I cant just assume it will always be 5 in my code logic as it could have less than 5 answers), with a sum of the score of the up to 5 rows.
Instead what I seem to get back is the total number of matching rows (where user is 1) as the count, and the sum of the score for those rows. The numbers don't change whether I put LIMIT 1
or LIMIT 5
or even LIMIT 50
.
What I believe will work in this situation is this instead
SELECT COUNT(*), SUM(score) FROM (SELECT * FROM answers WHERE user=1 LIMIT 5) AS a
But that seems a little convoluted for such a simple query, and as it's in a high traffic script, I want it to be as performant as possible.
Am I missing something? I did find this bug report from a few years back which seems to be related to this "problem", but I'm assuming it's not actually a bug?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…