在多个行的COUNT上过滤分组结果

时间:2013-12-17 20:57:12

标签: mysql sql

我基本上有一个非常简单的查询,比如

SELECT accounts . * , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
ORDER BY COUNT(receive) DESC

我尝试将其更改为以下内容并且失败了

SELECT accounts . * , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
    AND total_accounts < 10
GROUP BY followings.receive
ORDER BY COUNT(receive) DESC

Unknown column 'total_counts' in 'where clause'

我很抱歉发布了这么简单的问题,但我的思绪现在很难以理解

3 个答案:

答案 0 :(得分:3)

首先:删除表格与* 之间的空格:accounts.*

第二:你不能在聚合表达式上使用where。您需要使用having

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
HAVING total_accounts < 10
ORDER BY COUNT(receive) DESC

关于选择如何运作的小指南:

SELECT "Fields and expressions"
FROM "Tables, views and / or subqueries"
WHERE "Conditions to apply on the raw data (contained directly in the FROM clause)"
GROUP BY "Grouping fields"
HAVING "Conditions to apply on the grouped data or (aggregate) expressions"

答案 1 :(得分:2)

要在 GROUP BY子句之前过滤,使用WHERE,然后过滤 ,请使用HAVING。由于count的聚合在分组期间发生,因此它在WHERE子句中给出了错误 - 在执行的那一点上它还不知道。改为:

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive
HAVING count(receive) < 10
ORDER BY COUNT(receive) DESC

答案 2 :(得分:0)

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
GROUP BY followings.receive  --<-- You need to GROUP BY All the columns
                                 -- In your select that are not containted 
                               -- in any Aggregate Function i.e accounts.*


ORDER BY total_counts DESC  --<-- ORDER BY you need to use the Alias

查询2

SELECT accounts.* , COUNT(receive) as total_counts
FROM followings
LEFT JOIN accounts ON followings.receive = accounts.account_id
WHERE accounts.status <1
  --  AND total_accounts < 10 --<-- Where Clause Filters the Rows
                                -- Before doing any aggregates you
                                -- need to use HAVING Clause when checking
                                -- against aggregated values

GROUP BY followings.receive   --<-- You need to GROUP BY All the columns
                                 -- In your select that are not containted 
                               -- in any Aggregate Function i.e accounts.*
HAVING total_accounts < 10
ORDER BY total_counts DESC --<-- ORDER BY you need to use the Alias