如何在where子句中包含汇总列?

时间:2019-03-07 23:56:48

标签: mysql sql

我有一个2列的表farmer_crops,用于存储农民与其耕种的作物之间的关系。农民可以种植一种或多种农作物。下面的查询为我提供了不同的农民和他们种植的农作物。我怎样才能使种植农作物的农民总数超过一(my_crops> 1)?

select distinct farmer_id, count(crop_id) as my_crops 
from farmer_crops 
group by farmer_id

[edit]使用GMB的提示,下面的查询向我提供了总共2330行,这是正确的。

SELECT farmer_id, count(crop_id) as my_crops 
FROM farmer_crops 
GROUP BY farmer_id
HAVING count(crop_id) > 1

但是,我真正想要的是下面的查询,只是总数,但是total_farmers列返回的数字是8330,这是错误的。

SELECT count(farmer_id) as total_farmers 
FROM farmer_crops
HAVING count(crop_id) > 1

1 个答案:

答案 0 :(得分:2)

不能在WHERE子句中使用聚合表达式的条件。您需要改用HAVING

SELECT farmer_id, count(crop_id) as my_crops 
FROM farmer_crops 
GROUP BY farmer_id
HAVING count(crop_id) > 1

WHERE子句不同,HAVING子句在GROUP BY子句之后

NB:SELECT DISTINCT通常与GROUP BY没有任何意义,我将其删除。