jjzjj

ruby-on-rails - 分组错误 : ERROR: column must appear in the GROUP BY clause or be used in an aggregate function

coder 2023-07-19 原文

我的 Controller 中有代码按最高平均评论评级对专辑进行排名(使用此解决方案中的代码 How to display highest rated albums through a has_many reviews relationship):

@albums = Album.joins(:reviews).select("*, avg(reviews.rating) as average_rating").group("albums.id").order("average_rating DESC")

此代码在我的开发环境 (sqlite3) 中完美运行,但是当我将代码推送到 heroku 和 postgresql 时,出现此错误:

PG::GroupingError: ERROR:  column "reviews.id" must appear in the GROUP BY clause or be used in an aggregate function

我意识到这是一个相当普遍的问题,我对 SQL 有点缺乏经验,所以我在重构代码以使其在我的开发和生产环境中都能正常工作时遇到了麻烦。

最佳答案

您不能选择 reviews.id(通过通配符 * 隐式选择)而不将其添加到 GROUP BY 子句或应用聚合函数,如 avg()。解决方案是执行以下操作之一:

  1. 从您的选择中删除通配符*
  2. 将字段 reviews.id 添加到您的组子句
  3. 明确选择 reviews.id 并对其应用聚合函数(例如 sum(reviews.id))
  4. 将通配符 * 替换为特定于表的通配符 albums.*

第二个和第三个选项在您的场景中没有多大意义。 根据您的评论,我添加了选项四。

关于ruby-on-rails - 分组错误 : ERROR: column must appear in the GROUP BY clause or be used in an aggregate function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20942477/

有关ruby-on-rails - 分组错误 : ERROR: column must appear in the GROUP BY clause or be used in an aggregate function的更多相关文章

随机推荐