0

我有声明

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子句,而无需在上面返回的整个结果集上编写嵌套查询或连接语句?

4

2 回答 2

3
SELECT COUNT(*) as num_requests, ip_address 
FROM requests
GROUP BY ip_address
HAVING num_requests = 3
ORDER BY num_requests DESC
于 2012-11-27T10:36:48.823 回答
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,COUNTetc之类的WHERE聚合不起作用。所以你必须使用后者。

于 2012-11-27T10:40:38.093 回答