开发者

How do I count MySQL entries with a HAVING criterion

开发者 https://www.devze.com 2023-01-17 06:01 出处:网络
So usually you can just do SELECT COUNT(field.id) FROM table WHERE field.id >开发者_开发技巧; 100

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


Well, COUNT works BEFORE HAVING is applied to the result set. So if you need to count their number - you have to wrap your query with another one.

SELECT COUNT(*) FROM (
    SELECT field.id * 10 AS foo FROM table HAVING foo > 100
)


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:

SELECT field.id * 10 AS foo 
  FROM table 
 WHERE field.id * 10 > 100

MySQL does support referencing a column alias in the GROUP BY or HAVING clause. It doesn't require using backticks, but I have seen instances that wouldn't work (non-reserved words) until backticks were present:

SELECT field.id * 10 AS foo 
  FROM table 
HAVING `foo` > 100

I don't recommend this approach - it's supported on SQL Server, but not Oracle...

The HAVING clause is like the WHERE clause, the difference is that the HAVING clause supports aggregate functions without needing them to be wrapped in a subquery.


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

SELECT COUNT(field.id), field.id * 10 AS foo FROM table HAVING foo > 100

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 -

SELECT COUNT(field.id) FROM table HAVING COUNT(field.id) > 100

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消