Rails(PG :: GroupingError:ERROR:列必须出现在GROUP BY子句中或在聚合函数中使用 [英] Rails (PG::GroupingError: ERROR: column must appear in the GROUP BY clause or be used in an aggregate function

查看:120
本文介绍了Rails(PG :: GroupingError:ERROR:列必须出现在GROUP BY子句中或在聚合函数中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的本地环境中,此查询与sqlite3完美配合

In my local this query work perfect with sqlite3

 def Event.most_like
   select("events.*, count(like_events.event_id) as likes_count")
   .joins(:like_events).group(:event_id).order("likes_count 
    DESC").limit(4)
 end

但是在部署heroku时出现了一些错误 PG :: GroupingError:错误:"events.id"列必须出现在GROUP BY子句中或在聚合函数中使用

but i got some error when deploy heroku PG::GroupingError: ERROR: column "events.id" must appear in the GROUP BY clause or be used in an aggregate function

有人可以帮我解决这个问题吗?

Can someone help me fix this?

推荐答案

作为消息, Select 子句中的所有字段都必须出现在 GROUP BY 或聚合函数中.在这种情况下,请选择 Event 的所有字段,以便包含 events.id 的字段需要满足上述要求.

As the message, all fields in Select clause must appear in the GROUP BY or in aggregate function. In this case, you select all fields of Event so that the fields, which includes events.id, need to satisfy above requirement.

要解决此问题,我建议更改功能以仅选择事件的ID和likes_count,如下所示:

To fix that, I suggest to change function to select only event's id and likes_count as below:

def Event.most_like
  select("events.id, count(like_events.event_id) as likes_count").
  joins(:like_events).
  group('events.id').
  order("likes_count DESC").
  limit(4)
end

如果您仍然需要获取事件记录,则可以根据其ID提取这些记录.

If you still need to get event records, you can fetch those records based on their ids.

这篇关于Rails(PG :: GroupingError:ERROR:列必须出现在GROUP BY子句中或在聚合函数中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆