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

问题描述

我正在尝试创建一个留下评论的独特患者名单。这些代码字很好,直到我上传到heroku,它在postgresql中不起作用。



这是我创建列表的Ruby .erb代码:

 <%@ comments.group(:patient_id).each_with_index do |评论,索引| %GT; 
< div class =profile-post color-one>
< span class =profile-post-numb><%= index + 1%>< / span>
< div class =profile-post-in>
< h3 class =heading-xs>< a><%= link_to#{comment.patient.first_name}#{comment.patient.last_name},comment_path(comment)%> ;< / A>< / H3>
< p>来自<%= time_ago_in_words(comment.created_at)的最新评论>前< i class =pull-right><%= link_to编辑,edit_comment_path(评论)%> <%= link_to删除,comment_path(评论),方法:: delete,data:{confirm:'您确定要删除'}%>< / i>< / p>
< / div>
< / div>
<%end%>

@comments在控制器中定义为:

  def index 
@comments = current_clinician.comments.order(created_at desc)
end

heroku日志给我这个错误信息:

我尝试了其他SO问题的解决方案,例如作为。其中说我应该将字段comments.id添加到我的group子句中:

 <%@ comments.group(:patient_id ,:comments.id)。each_with_index do | comment,index | %GT; 

这样可以摆脱heroku上的错误,但会破坏组命令的作用 - 它不再只是显示独特的患者,而是列出所有这些患者。



我也尝试了。这说我应该改变ORDER BY:

  @comments = current_clinician.comments.order(substring(created_at,1.8) desc)

在本地给出这个错误:

我知道这是一个常见问题,我对SQL不熟悉我无法获取代码,因此它可以在我的开发和生产环境中使用。我读过的所有答案都没有使用Ruby来获取SQL,并且超过了我的经验级别。

解决方案

您无法合并Postgres中除 some_column 以外的 SELECT * 是PK),因为这是一个矛盾。所有非汇总列(用于 SELECT , HAVING 或 ORDER BY 子句)必须位于 GROUP BY 列表中 - 其中主键列可以替换表中的所有列。否则,它是未定义哪个值要从汇总集中选择。




$ b

You seem to want a list of unique patients that have commented, with the latest comment each. The simplest way in Postgres is with DISTINCT ON:

SELECT DISTINCT ON (patient_id) *
FROM   comments
WHERE  clinician_id = $1
ORDER  BY patient_id, created_at DESC NULLS LAST;

But this won't fly with SQLite - which should not be in the loop to begin with:

NULLS LAST is only relevant if created_at can be NULL:

Details for DISTINCT ON:

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

07-16 08:25
查看更多