MySQL到Postgres group_by错误

时间:2014-05-14 17:29:39

标签: mysql ruby-on-rails ruby-on-rails-3 postgresql ruby-on-rails-4

以下查询在MySQL中工作正常(由rails生成):

SELECT
   sum(up_votes) total_up_votes 
FROM
   "answers" 
WHERE
   "answers"."user_id" = 100
ORDER BY
   "answers"."id" ASC

然而,它在Postgres中出现以下错误:

PG::GroupingError: ERROR:  column "answers.id" must appear in the GROUP BY clause or be used in an aggregate function

修改更新的查询。以下是执行此查询的Rails模型:

class User < MyModel
  def top?
    data = self.answers.select("sum(up_votes) total_up_votes").first
    return (data.total_up_votes.present? && data.total_up_votes >= 10)
  end
end

1 个答案:

答案 0 :(得分:2)

查询可以在MySQL中执行,但我怀疑它“工作正常”。它只返回一行,因此排序毫无意义。

您的问题对于您实际想要做的事情是模糊的,但这应该会在两个数据库中产生与查询相同的结果:

SELECT sum(up_votes) as total_up_votes
FROM answers
WHERE user_id = 100;