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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16297083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:53:32  来源:igfitidea点击:

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

ruby-on-railspostgresqlactiverecord

提问by Teej

Relationships:

关系:

Item belongs to Product
Product belongs to User

Item model scope:

产品型号范围:

  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')
  }

The above results in the following SQL statement:

以上结果产生以下 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

The problem here is that an error occurs:

这里的问题是出现了一个错误:

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...

What could be a fix for this?

什么可以解决这个问题?

采纳答案by AlexBrand

From the error you can see that you should try including users.idin the GROUP BYclause:

从错误中您可以看到您应该尝试users.idGROUP BY子句中包含:

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