【问题标题】:Invalid use of GROUP BY operator after WHERE clauseWHERE 子句后无效使用 GROUP BY 运算符
【发布时间】:2015-09-20 17:59:34
【问题描述】:

以下查询成功返回打印最多的特定用户(按 id):

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints`
INNER JOIN `user` on file_prints.user_id = user.user_id GROUP BY
file_prints.user_id 
ORDER BY sum(print_pages)

当我引入 where 子句来尝试消除根本没有打印的用户(即 where sum(print_pages) == 0)时,我编写了以下查询:

SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints`
INNER JOIN `user` on file_prints.user_id = user.user_id WHERE
sum(print_pages) > 0 GROUP BY file_prints.user_id 
ORDER BY sum(print_pages)

并得到以下错误:

 #1111 - Invalid use of group function 

如何消除 sum(print_pages) 为 0 的结果?

【问题讨论】:

    标签: mysql group-by where-clause


    【解决方案1】:

    这是因为您不能在 WHERE 子句中使用聚合函数。所以,像这样使用HAVING 子句:

    SELECT file_prints.user_id, user.major, sum(print_pages) 
    FROM `file_prints`
    INNER JOIN `user` on file_prints.user_id = user.user_id
    GROUP BY file_prints.user_id
    HAVING sum(print_pages) > 0 
    ORDER BY sum(print_pages)
    

    【讨论】:

      【解决方案2】:

      在处理聚合时,您需要使用 having 关键字:

      SELECT file_prints.user_id, user.major, sum(print_pages) FROM `file_prints`
      INNER JOIN `user` on file_prints.user_id = user.user_id 
      GROUP BY file_prints.user_id 
      HAVING sum(print_pages) > 0 
      ORDER BY sum(print_pages)
      

      【讨论】:

        猜你喜欢
        • 2022-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-20
        • 2011-09-25
        相关资源
        最近更新 更多