PG :: GroupingError未在聚合函数中使用

时间:2014-11-10 02:42:49

标签: postgresql activerecord grouping aggregate-functions

我看到了这个错误:

ActiveRecord::StatementInvalid (PG::GroupingError: ERROR:  column "playlistships.updated_at" must appear in the GROUP BY clause or be used in an aggregate function
2014-11-10T01:25:00.821301+00:00 app[web.1]:   app/controllers/playlists_controller.rb:9:in `index'

当我运行此查询时:

Playlistship.select("playlist_id, max(updated_at)").order('updated_at desc').group(:playlist_id).paginate(:page => params[:page], :per_page => 12)

我似乎在聚合函数中使用updated_at,所以我不确定下一步该怎么做?

1 个答案:

答案 0 :(得分:0)

问题:如果我正确地提出了问题,那么您正尝试运行类似的内容:

SELECT playlist_id, max(updated_at)
FROM PlayListChip
GROUP BY playlist_id
ORDER BY updated_at DESC
LIMIT 12 OFFSET 0

原因:错误是因为您尝试按列排序(updated_at)而不是'聚合'updated_at ...如果您考虑一下,这将无效。这是因为 ORDER BY 需要与SELECT字段是相同的聚合(或者它必须是GROUP BY字段之一)。

解决方案:您可能想要替换

Playlistship.select("playlist_id, max(updated_at)").order('updated_at desc').group(:playlist_id).paginate(:page => params[:page], :per_page => 12)

Playlistship.select("playlist_id, max(updated_at)").order('max(updated_at) desc').group(:playlist_id).paginate(:page => params[:page], :per_page => 12)