我有两个表:评论和地区。 sql查询是:
SELECT comments.region,
COUNT(comments.region)
FROM comments, regions
WHERE comments.region = regions.id
GROUP BY comments.region;
结果表是(id,COUNT(comments.region)):
1 | 3
2 | 1
3 | 7
4 | 6
5 | 2
如何添加规则以过滤COUNT(comments.region)>所有行5?最后,我需要一个摘要表:
3 | 7
4 | 6
答案 0 :(得分:4)
使用HAVING
:
SELECT c.region, COUNT(*)
FROM comments c
INNER JOIN regions r
ON c.region = r.id
GROUP BY c.region
HAVING COUNT(*) > 5
备注:强>
我使用INNER JOIN
子句将显式ON
替换为隐式连接。正如@GordonLinoff所说,你应该避免在逗号WHERE
中加入逗号。我还在查询中引入了表别名,这使我们不必重复编写完整的表名。
答案 1 :(得分:1)
您在寻找HAVING
吗?
SELECT comments.region,
COUNT(comments.region)
FROM comments,
regions
WHERE comments.region = regions.id -- obsolete syntax: use JOIN instead
GROUP BY comments.region
HAVING COUNT(comments.region) > 5;
答案 2 :(得分:0)
您必须使用HAVING子句
SELECT comments.region, COUNT(comments.region)
FROM comments, regions
WHERE comments.region = regions.id
GROUP BY comments.region
HAVING COUNT(comments.region) > 5;
的更多详情,请参阅此处