Mysql2 ::错误:ORDER BY子句的表达式#2不在GROUP BY子句中,并且包含非聚合列

时间:2017-10-03 20:44:18

标签: mysql ruby-on-rails

我收到以下错误:

Mysql2::Error: Expression #2 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'database_name_development.posts.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by: SELECT YEAR(created_at) AS year, MONTHNAME(created_at) AS month, COUNT(id) AS total FROM {帖子{1}}

这是我的模型方法

GROUP BY year, month ORDER BY year DESC, MONTH(created_at) DESC

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

从MySQL 5.6开始,允许SELECT表达式(或相关ORDER BY)中的列的旧默认行为在使用聚合时在GROUP BY中也不会出现更严格(和其他RDBMS一样)。

由于MONTH(created_at)中有ORDER BY以数字方式对月份进行排序,但SELECTGROUP BY中没有等效表达式,因此违反了MySQL对{{1}的要求}}。解决方案是将数字GROUP BY表达式添加到MONTH()SELECT,以便分组可以正确聚合。这不应该影响性能。

GROUP BY

如果将def self.archives # Include a MONTH() expression in SELECT Post.unscoped.select("YEAR(created_at) AS year, MONTHNAME(created_at) AS month, MONTH(created_at) AS monthnum, COUNT(id) AS total") # Group with it as well .group("year, month, monthnum") # sort with the column alias .order("year DESC, monthnum DESC") end 添加到MONTH(created_at) AS monthnum,可以将.select()保留在.group()之外(因为您实际上不需要返回数值)。如果确实有效,则无法在.group().order()中使用别名,而必须使用完整表达式。我不确定这会毫无错误地发挥作用,但相信它可能。

def self.archives
    Post.unscoped.select("YEAR(created_at) AS year, MONTHNAME(created_at) AS month, COUNT(id) AS total")
        # Add the expression to GROUP BY but not SELECT
        .group("year, month, MONTH(created_at)")
        .order("year DESC, MONTH(created_at) DESC")
end