错误代码1111。无效使用组功能

Posted

技术标签:

【中文标题】错误代码1111。无效使用组功能【英文标题】:Error Code 1111. Invalid use of group function 【发布时间】:2014-04-04 05:14:05 【问题描述】:

所以这行得通:

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

但我只需要获取大于 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

那时我得到了:

错误代码1111。组函数使用无效

也就是说,当我在WHERE中添加这个条件时它失败了:

AND ROUND(100*(SUM(ci.population)/c.population)) > 30

【问题讨论】:

除了使用having 子句之外:您对group by 的一般用法在(标准)SQL 中是无效的。 mysqlgroup by 的草率实现允许在任何其他DBMS 中失败的东西。有关详细信息,请阅读:mysqlperformanceblog.com/2006/09/06/… 和此:rpbouman.blogspot.de/2007/05/debunking-group-by-myths.html 【参考方案1】:

所以你必须把这个条件移到 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

【讨论】:

不要忘记group by 的这种无效使用只会返回可能不是正确结果的随机数据。【参考方案2】:

您在 where 子句中使用聚合函数,这在 SQL 中是做不到的。

改用HAVING 子句:

WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30

【讨论】:

以上是关于错误代码1111。无效使用组功能的主要内容,如果未能解决你的问题,请参考以下文章

遇到 SQL 错误 1111 的问题

获取错误 #1111 - 组函数的使用无效

MySQL 错误 #1111 - 组函数的使用无效

SQLSTATE[HY000]: 一般错误: 1111 无效使用组函数 (SQL: select GROUP_CONCAT(sum(documents.grand_total) SEPARATOR &

MySQL 错误 #1111

错误笔记MyBatis SQLException: 无效的列类型: 1111