[英]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.