将表列添加到Group by子句 - Ruby on Rails - Postgresql

bga*_*oci 5 ruby postgresql ruby-on-rails heroku

我正在尝试使用Heroku,显然Postgresql比聚合函数的SQL要严格得多.当我向Heroku推送时,我收到一个错误,说明如下.

在另一个问题上,我问我收到了一些指导,说我应该将列添加到我的group by子句中,我不知道该怎么做.请参阅下面的完整错误和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):
Run Code Online (Sandbox Code Playgroud)

PostsController

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
Run Code Online (Sandbox Code Playgroud)

Bil*_*win 3

MySQL 和 SQLite 非常灵活,它们允许选择列表中的列无需在子句中命名GROUP BY(并且不在像 之类的聚合函数内COUNT())。但这种程度的灵活性可能会导致查询不明确。

PostgreSQL 仅与 ANSI SQL 标准一样严格。我测试过的所有其他数据库(Oracle、Microsoft、IBM DB2、Firebird)在这个问题上的表现都与 PostgreSQL 类似。

您需要做的就是使posts选择列表中的列列表与子句中命名的列相匹配GROUP BY。通过选择更少的列或将列添加到:group.

我不是 Rails 专家,而且我找不到如何将多个列作为参数传递给:group. 查看 active_record/base.rb 的代码,它似乎只是将选项值复制到文字 SQLGROUP BY子句中。所以我想(没有尝试过)你可以这样做:

...
:group => "posts.post_id, posts.foo, posts.bar, posts.baz", 
...
Run Code Online (Sandbox Code Playgroud)

请注意,您必须命名选择列表中不属于聚合函数的每一列。