如何写子句:WHERE num = ...用于语句SELECT COUNT(*)as num ...?

时间:2012-11-27 10:36:00

标签: mysql

我有声明

SELECT COUNT(*) as num_requests, ip_address FROM requests
GROUP BY ip_address
ORDER BY num_requests DESC;

当我使用以下子句WHERE num_requests = 3时,我收到语法错误

SELECT COUNT(*) as num_requests, ip_address 
FROM requests
WHERE num_requests = 3
GROUP BY ip_address
ORDER BY num_requests DESC;

'where子句'中的未知列'num_requests'

有没有办法可以使用这个WHERE子句而不在上面返回的整个结果集上编写嵌套查询或连接语句?

2 个答案:

答案 0 :(得分:3)

SELECT COUNT(*) as num_requests, ip_address 
FROM requests
GROUP BY ip_address
HAVING num_requests = 3
ORDER BY num_requests DESC

答案 1 :(得分:3)

您需要having:)

SELECT COUNT(*) as num_requests, ip_address FROM requests
GROUP BY ip_address
HAVING COUNT(*) = 3
ORDER BY num_requests DESC;

添加关于无法使用WHERE的原因的说明,但HAVING:使用SUM, MIN,MAX,AVG,COUNTWHERE等汇总无效。所以你必须使用后者。