PG::Error in GROUP BY clause

后端 未结 2 1678
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 23:51

I couldn\'t think of a better way to refactor the below code (see this question), though I know it\'s very ugly. However, it\'s throwing a Postgres error (not with SQLite):<

相关标签:
2条回答
  • 2020-12-04 00:37

    Craig's answer explains the issue well. Active Record will select * by default, but you can override it easily:

    @user.articles.select("publication, sum(twitter_count) as twitter_count").group(:publication).each do |row|
      p row.publication # "BBC"
      p row.twitter_count # 45
    end
    
    0 讨论(0)
  • 2020-12-04 00:43

    When using GROUP BY you cannot SELECT fields that are not either part of the GROUP BY or used in an aggregate function. This is specified by the SQL standard, though some databases choose to execute such queries anyway. Since there's no single correct way to execute such a query they tend to just pick the first row they find and return that, so results will vary unpredictably.

    It looks like you're trying to say:

    "For each publication get me the sum of the twitter, facebook and linkedin counts for that publication".

    If so, you could write:

    SELECT publication,
           sum(twitter_count) AS twitter_sum,
           sum(linkedin_count) AS linkedin_sum,
           sum(facebook_count) AS facebook_sum
    FROM "articles" 
    WHERE "articles"."user_id" = 1 
    GROUP BY publication;
    

    Translating that into ActiveRecord/Rails ... up to you, I don't use it. It looks like it's pretty much what you tried to write but ActiveRecord seems to be mangling it, perhaps trying to execute the sums locally.

    0 讨论(0)
提交回复
热议问题