mysql - 将 MySQL 切换到 Postgres : "column must appear in the GROUP BY clause or be used in an aggregate function"

标签 mysql ruby-on-rails database postgresql ruby-on-rails-4

将 Rails 应用程序从 MySQL 切换到 Postgres 会出现以下错误:

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

这里是有问题的范围:

class User < MyModel
  def self.top_contacts(timeframe = 1.week.ago, limit = 5)
    Contact.unscoped
          .where('created_at between ? and ?', timeframe, Time.now)
          .group(:user_id)
          .order('sum(score) DESC')
          .limit(limit)
          .includes(:user)
          .collect{|x| x.user}
  end
end
  1. 如何解决这个问题?
  2. 难道使用 Rails 作为数据库抽象层不能确保切换数据库应该无缝工作吗?

最佳答案

问题出在 SQL 层面,这在您的 ORM 层是不可见的。问题恰恰出在 RoR ORM 上,因为它似乎生成了一个 MySQL 友好的查询,该查询使用了 MySQL 的一个非凡特性,而 postgresql 没有。

快速解决方案:将 contacts.id 也提供给您分组的列:

.group("user_id, contacts.id");

关于mysql - 将 MySQL 切换到 Postgres : "column must appear in the GROUP BY clause or be used in an aggregate function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475476/

相关文章:

ruby-on-rails - 如何在rails查询中找到有多个评论的帖子?

ruby-on-rails - 未从 css 文件 Heroku 和 S3 引用 Rails 4 供应商 Assets 图像

MYSQL 连接返回三重结果

Java/JDBC - 使用 TableModels 显示单个数据

php - 如何知道你是否在 PHP/MySQL mysql_fetch_array() 中的第一条记录上

php - 如何在 mysql 表中自动链接上传

ruby-on-rails - 蜻蜓 : cleanup files during tests

sql - Access 2007、Oracle 和 SQL Server 中的列/表分隔符

database - 如何更改 SQL Server Compact Edition 表架构中的列顺序?

使用 $stmt->get_result()->fetch_assoc() 时出现 PHP 错误(500 内部服务器错误);