SQL查询按COUNT过滤

时间:2017-03-13 08:38:27

标签: sql group-by

我有两个表:评论和地区。 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

3 个答案:

答案 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;

有关HAVING条款https://www.w3schools.com/sql/sql_having.asp

的更多详情,请参阅此处