我有一个2列的表farmer_crops,用于存储农民与其种植的农作物之间的关系.农民可以种植一种或多种农作物.下面的查询为我提供了不同的农民和他们种植的农作物.我怎样才能使种植农作物的农民总数超过一(my_crops> 1)?
select distinct farmer_id,count(crop_id) as my_crops
from farmer_crops
group by farmer_id
[编辑]使用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
最佳答案
聚集表达式的条件不能在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子句之后.
注意:SELECT DISTINCT通常对于GROUP BY没有意义,我将其删除.