如何使用 HAVING 标准对 MySQL 条目进行计数
因此,通常您可以这样做
SELECT COUNT(field.id) FROM table WHERE field.id > 100
,并且 COUNT(field) 将返回符合 field.id > 条件的条目数。 100
但是,如果您要对使用 HAVING 条件指定的条目进行计数(例如
SELECT COUNT(field.id), field.id * 10 AS foo FROM table HAVING foo > 100
在本例中代码不起作用),该怎么办...
我该如何对通过 HAVING 子句指定的条件进行计数的条目进行计数?
提前致谢
So usually you can just do
SELECT COUNT(field.id) FROM table WHERE field.id > 100
and COUNT(field) will return the number of entries that has the criterion of field.id > 100
But then what if you what to count entries specified with the HAVING criterion such as
SELECT COUNT(field.id), field.id * 10 AS foo FROM table HAVING foo > 100
the code wouldn't work in this case....
How do I go about counting entries whose criterion are specified via the HAVING clause?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,
COUNT
的工作BEFOREHAVING
应用于结果集。因此,如果您需要计算它们的数量 - 您必须用另一个查询来包装您的查询。Well,
COUNT
works BEFOREHAVING
is applied to the result set. So if you need to count their number - you have to wrap your query with another one.我无法按原样运行任何一个查询 - 他们给我一个 1140 错误,提示“使用不带 GROUP BY 子句的聚合”(即:
COUNT(field.id)
)。一切似乎都与聚合无关,只是能够引用列别名进行比较...最广泛支持的方式是:
MySQL 确实支持在 GROUP BY 中引用列别名或
HAVING
子句。它不需要使用反引号,但我见过在反引号出现之前无法工作的实例(非保留字):我不推荐这种方法 - 它在 SQL Server 上受支持,但在 Oracle 上不受支持
...
HAVING
子句类似于WHERE
子句,不同之处在于HAVING
子句支持聚合函数,而不需要将它们包装在子查询中。I can't run either query as-is - they give me a 1140 error for "using an aggregate without a GROUP BY clause" (IE:
COUNT(field.id)
). Everything appears not to relate to the aggregate at all, just the ability to reference the column alias for comparison...The most widely supported means is:
MySQL does support referencing a column alias in the
GROUP BY
orHAVING
clause. It doesn't require using backticks, but I have seen instances that wouldn't work (non-reserved words) until backticks were present:I don't recommend this approach - it's supported on SQL Server, but not Oracle...
The
HAVING
clause is like theWHERE
clause, the difference is that theHAVING
clause supports aggregate functions without needing them to be wrapped in a subquery.免责声明 - 我只在 SQL Server 上对此进行了测试,
在这种情况下,HAVING 只会对整个返回集执行任何聚合查询。首先,无法运行,
因为field.id不包含在定义组或聚合函数的子句中;它只是无法编译。
话虽如此,如果计数大于 100,以下 SQL -
将返回表中的行数。如果不是,则不会得到任何结果。
您有一个具体的问题吗?你想数什么?
DISCLAIMER - I've only tested this on SQL Server
HAVING in this case will only perform any aggregate queries over the entire returned set. First of all, you can't run
because field.id is not contained in a clause that defines a group or an aggregate function; it just doesn't compile.
With that said, the following SQL -
will return the count of rows in the table if the count is greater than 100. If it's not, you'll get no result.
Do you have a specific problem in mind? What are you trying to count?