mysql 在where条件下使用按列分组
我怎样才能使这个查询工作:
SELECT column1.....,SUM(Hits) AS Hits
FROM table
WHERE SUM(Hits) > 100
GROUP BY column1.....
问题是where子句,mysql显示错误:
Error Code : 1111
Invalid use of group function
我尝试将查询更改为:
SELECT column1.....,SUM(Hits) AS Hits
FROM table
WHERE Hits > 100
GROUP BY column1.....
它没有帮助。
谢谢
How can I make this query work :
SELECT column1.....,SUM(Hits) AS Hits
FROM table
WHERE SUM(Hits) > 100
GROUP BY column1.....
The problem is the where clause, mysql display error :
Error Code : 1111
Invalid use of group function
I try to change the query to :
SELECT column1.....,SUM(Hits) AS Hits
FROM table
WHERE Hits > 100
GROUP BY column1.....
It did not help.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
错误的原因是您不能在
WHERE
子句中使用聚合函数,也不能使用聚合函数对派生列使用列别名。这些只能在HAVING
子句中使用,该子句需要定义GROUP BY
子句(如果尚不存在)。我不建议在 GROUP BY 或 HAVING 子句中使用列别名 - 存在查询无法移植到其他数据库的风险。 SQL Server 是我所知道的唯一支持在 GROUP BY 或 HAVING 子句中使用列别名的数据库。
The reason for the error is that you can not use aggregate functions, or column aliases to derived columns using aggregate functions, in the
WHERE
clause. These can only be used in theHAVING
clause, which requires defining aGROUP BY
clause (if it doesn't already exist).I don't recommend using the column alias in
GROUP BY
orHAVING
clauses - there's a risk that the query will not be portable to other databases. SQL Server is the only other database that I'm aware of that supports column aliases in theGROUP BY
orHAVING
clauses.