列“users.id”必须出现在GROUP BY子句中或用于聚合函数

时间:2013-04-30 09:57:03

标签: ruby-on-rails postgresql activerecord

关系:

Item belongs to Product
Product belongs to User

物品型号范围:

  scope :search, ->(search_term) {
    select('products.name, users.*, products.brand, COUNT(products.id)')
    .joins(:product => :user)
    .where('users.name = ? OR products.brand = ?', search_term, search_term)
    .group('products.id')
  }

以上结果出现在以下SQL语句中:

SELECT products.name, users.*, products.brand, COUNT(products.id) FROM "items" 
INNER JOIN "products" ON "products"."id" = "items"."product_id" 
INNER JOIN "users" ON "users"."id" = "products"."user_id" 
WHERE (users.name = 'Atsuete Lipstick' OR products.brand = 'Atsuete Lipstick') 
GROUP BY products.id

这里的问题是发生错误:

ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "users.id" 
must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT products.name, users.*, products.brand, COUNT(product...

有什么可以解决这个问题?

1 个答案:

答案 0 :(得分:-6)

从错误中您可以看到您应该尝试在users.id子句中加入GROUP BY

 .group('products.id, users.id')