如何使用LEFT JOIN和GROUP BY选择最小count()的记录?

时间:2015-04-15 20:31:10

标签: mysql sql

使用以下查询,我会得到所有页面的列表和访问者数量。

SELECT 
 pages.id AS id,
 count(visitors.id) AS volume
FROM pages
 LEFT JOIN visitors ON 
 pages.id = visitors.page_id
GROUP BY pages.id
ORDER BY volume DESC

这成功返回类似

的内容
+--+------+
|id|volume|
+--+------+
|1 |288   |
|2 |355   |
|3 |80    |
etc...

现在,我只想选择卷(访客行数)超过100的页面。

我试过了:

SELECT 
 pages.id AS id,
 count(visitors.id) AS volume
FROM pages
 LEFT JOIN visitors ON 
 pages.id = visitors.page_id
WHERE
 volume > 100
GROUP BY pages.id
ORDER BY volume DESC

但是这会导致错误:#1054 - 未知列'音量'在' where子句'

使用 WHERE count(visitors.id)> 100 给出了同样的错误。如何过滤这些结果?

2 个答案:

答案 0 :(得分:1)

您应该在having子句中使用count(visitors.id)

SELECT 
    pages.id AS id,
    count(visitors.id) AS volume
FROM pages
LEFT JOIN visitors ON pages.id = visitors.page_id
GROUP BY pages.id
HAVING count(visitors.id) > 100
ORDER BY volume DESC

答案 1 :(得分:1)

您正在寻找HAVING条款:

SELECT 
 pages.id AS id,
 count(visitors.id) AS volume
FROM pages
 LEFT JOIN visitors ON 
 pages.id = visitors.page_id
GROUP BY pages.id
HAVING count(visitors.id) > 200
ORDER BY volume DESC

您可以根据GROUP BY的聚合结果来考虑HAVING子句过滤结果。