简体   繁体   English

SQL查询按COUNT过滤

[英]SQL query filtered by COUNT

I have two tables: comments and regions. 我有两个表:评论和区域。 The sql query is: sql查询是:

SELECT comments.region, 
    COUNT(comments.region)
FROM comments, regions
WHERE comments.region = regions.id
GROUP BY comments.region;

The result table is (id, COUNT(comments.region)): 结果表是(id,COUNT(comments.region)):

1 | 3       
2 | 1
3 | 7
4 | 6
5 | 2

How I can add rule to filter all rows where COUNT(comments.region) > 5? 如何添加规则以过滤COUNT(comments.region)> 5的所有行? Finally I need to get a summary table: 最后,我需要获得一个汇总表:

3 | 7
4 | 6

Use HAVING : 使用HAVING

SELECT c.region, COUNT(*)
FROM comments c
INNER JOIN regions r
    ON c.region = r.id
GROUP BY c.region
HAVING COUNT(*) > 5

Notes: 笔记:

I replaced your implicit join with an explicit INNER JOIN using an ON clause. 我使用一个ON子句将您的隐式INNER JOIN替换为显式的INNER JOIN As @GordonLinoff likes to say, you should avoid putting commas into the WHERE clause. 就像@GordonLinoff喜欢说的那样,您应该避免在WHERE子句中添加逗号。 I also introduced table aliases into the query, which relieve us from having to write the full table name repeatedly. 我还在查询中引入了表别名,这使我们不必重复编写完整的表名。

Are you looking for HAVING ? 您在寻找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;

You have to use the HAVING clause 您必须使用HAVING子句

SELECT comments.region, COUNT(comments.region)
  FROM comments, regions
  WHERE comments.region = regions.id
  GROUP BY comments.region
  HAVING COUNT(comments.region) > 5;

See here for more details on HAVING clause https://www.w3schools.com/sql/sql_having.asp 有关HAVING子句的更多详细信息,请参见此处https://www.w3schools.com/sql/sql_having.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM