简体   繁体   English

带有LIMIT的MySQL COUNT

[英]MySQL COUNT with LIMIT

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. 我想要做的是SUM一列,但也要COUNT它总和的行数,限制不超过5行。 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. 我所期待的是COUNT(*)高达5(我不能假设它在我的代码逻辑中总是5,因为它可能少于5个答案), 最多 5行的得分总和。

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. 相反,我似乎得到的是匹配行的总数(用户为1)作为计数,以及这些行的得分总和。 The numbers don't change whether I put LIMIT 1 or LIMIT 5 or even LIMIT 50 . 无论我输入LIMIT 1还是LIMIT 5甚至是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? 几年前我确实发现了这个错误报告似乎与这个“问题”有关,但我认为它实际上并不是一个错误?

This is actually how your query works and is a normal behaviour. 这实际上是您的查询的工作方式,并且是正常行为。 Using LIMIT you will not limit the count or sum but only the returned rows. 使用LIMIT您不会限制计数或总和,只会限制返回的行。 So your query will return n rows as stated in your LIMIT clause. 因此,您的查询将返回LIMIT子句中所述的n行。 And since your query actually returns only one row, applying a (non-zero) limit has no effect on the results. 由于您的查询实际上只返回一行,因此应用(非零)限制对结果没有影响。

However, your second query will work as expected and is an established way of solving this problem. 但是,您的第二个查询将按预期工作,并且是解决此问题的既定方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM