MySQL 错误代码 1111。组函数的使用无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22141968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error Code 1111. Invalid use of group function
提问by user3374108
So this works:
所以这有效:
SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name
But I need to only grab the city_population_percent values greater than 30, so I try this:
但我只需要获取大于 30 的 city_population_percent 值,所以我试试这个:
SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
**AND ROUND(100*(SUM(ci.population)/c.population)) > 30**
GROUP BY c.name
And that's when I get:
那是我得到的时候:
Error Code 1111. Invalid use of group function
错误代码 1111。组函数的使用无效
That is, it fails when I add this condition in the WHERE
:
也就是说,当我在以下内容中添加此条件时它会失败WHERE
:
AND ROUND(100*(SUM(ci.population)/c.population)) > 30
回答by Surabhil Sergy
So you have to move this condition to the HAVINGclause
所以你必须把这个条件移到HAVING子句
SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30