我正在尝试使用 Heroku,显然 Postgresql 对于聚合函数比 SQL 严格得多。当我推送到 Heroku 时,我收到一条错误消息,说明如下。
On another question我问我收到了一些指导,说我应该按子句将列添加到我的组中,但我不确定该怎么做。请参阅下面的完整错误和 PostsControll#index。
SELECT posts.*, count(*) as vote_total FROM "posts" INNER JOIN "votes" ON votes.post_id = posts.id GROUP BY votes.post_id ORDER BY created_at DESC LIMIT 5 OFFSET 0):
帖子 Controller
def index
@tag_counts = Tag.count(:group => :tag_name,
:order => 'count_all DESC', :limit => 20)
conditions, joins = {}, :votes
@ugtag_counts = Ugtag.count(:group => :ugctag_name,
:order => 'count_all DESC', :limit => 20)
conditions, joins = {}, :votes
@vote_counts = Vote.count(:group => :post_title,
:order => 'count_all DESC', :limit => 20)
conditions, joins = {}, :votes
unless(params[:tag_name] || "").empty?
conditions = ["tags.tag_name = ? ", params[:tag_name]]
joins = [:tags, :votes]
end
@posts=Post.paginate(
:select => "posts.*, count(*) as vote_total",
:joins => joins,
:conditions=> conditions,
:group => "votes.post_id",
:order => "created_at DESC",
:page => params[:page], :per_page => 5)
@popular_posts=Post.paginate(
:select => "posts.*, count(*) as vote_total",
:joins => joins,
:conditions=> conditions,
:group => "votes.post_id",
:order => "vote_total DESC",
:page => params[:page], :per_page => 3)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
format.json { render :json => @posts }
format.atom
end
end
最佳答案
MySQL 和 SQLite 非常灵活,它们允许选择列表中的列无需在 GROUP BY
子句中命名(并且不在像 COUNT()
这样的聚合函数中) >).但这种程度的灵 active 可能会导致模棱两可的查询。
PostgreSQL 仅与 ANSI SQL 标准一样严格。我测试过的所有其他数据库(Oracle、Microsoft、IBM DB2、Firebird)在这个问题上的表现与 PostgreSQL 相似。
您需要做的是使您的选择列表中的posts
列列表与您的GROUP BY
子句中命名的列相匹配。通过选择较少的列或将列添加到 :group
来执行此操作。
我不是 Rails 专家,我找不到如何将多列作为参数传递给 :group
的示例。查看 active_record/base.rb 的代码,它似乎只是将选项值复制到文字 SQL GROUP BY
子句中。所以我想(没有尝试过)你可以这样做:
...
:group => "posts.post_id, posts.foo, posts.bar, posts.baz",
...
请注意,您必须为选择列表中不属于聚合函数的每个列命名。
关于ruby-on-rails - 将表列添加到 Group by 子句 - Ruby on Rails - Postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2699704/