首页 > 解决方案 > 在rails postgres上按字段分组结果

问题描述

我目前正在研究 rails,我正在尝试将查询结果按field.

查询由以下人员创建:
@orders = Order.includes(:product).where(user_id: current_user.id, paid: 0).group(:product_id)

它在 sqlite (dev env) 上运行良好,但在生产 (postgreSQL) 上会引发致命错误。

错误是:

ActionView::Template::Error (PG::GroupingError: ERROR:  column "orders.id" must appear in the GROUP BY clause or be used in an aggregate function

嗯..我在这里做错了什么?谢谢

标签: ruby-on-railspostgresqlgroup-by

解决方案


如果要在 postgres 中分组,则需要直接选择该列,或者需要调用使用该列的聚合函数。Count就是这样一个聚合函数,你可以在 Rails 中通过

@product_counts = Order.where(user: current_user, paid: 0).group(:product_id).count

Postgres 自动Count在您分组的列上执行,product_id在这种情况下。这会给你一个像这样的哈希:

{ product_id => count }

有关更多信息,请参见此处:https ://www.tutorialspoint.com/postgresql/postgresql_group_by.htm


推荐阅读