ruby-on-rails - 无法在 Rails 中使用 ActiveRecord 和 PostgreSQL 从每个组中选择不同的行

标签 ruby-on-rails ruby postgresql ruby-on-rails-4 activerecord

我的 ActiveRecord 查询有一个小问题。
我有一个产品模型,它看起来像:

#<Product id: nil, name: nil, price: nil, order_id: nil, created_at: nil, updated_at: nil, restaurant_id: nil>

现在我想在所有名称上选择 DISTINCT,并取回所有 Product 的属性。

我试过:

@products = Product.where(restaurant_id: !nil).group("products.name").order("name")

但是我得到了这个错误:

PG::GroupingError: ERROR:  column "products.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT  "products".* FROM "products"  WHERE "products"."rest...
                ^
: SELECT  "products".* FROM "products"  WHERE "products"."restaurant_id" = 1 GROUP BY products.name  

好的,然后我将 product_id 添加到我的查询中:

@products = Product.where(restaurant_id: !nil).group("products.name, products.id").order("name")

但此查询返回名称重复的产品。 所以我也尝试了这个:

@products = Product.where(restaurant_id: !nil).select("DISTINCT(NAME)").order("name")

但作为返回,我只得到了只有 ID 和名称的产品记录(很明显),所以如果这个查询返回正确的集合,我添加了我稍后需要的属性:

@products = Product.where(restaurant_id: !nil).select("DISTINCT(NAME), restaurant_id, price").order("name")

它也返回重复的名字。

您是否有任何解决方案或想法,如何解决 PostgreSQL 的此查询?
我习惯于这样写查询(在 MySQL 上),它是正确的:

@products = Product.where(restaurant_id: !nil).select("DISTINCT(NAME), restaurant_id, price").order("name")

为什么 PostreSQL 不接受该查询?

最佳答案

您应该将查询写成:-

Product.where
       .not(restaurant_id: nil)
       .select("DISTINCT ON(name) name, restaurant_id, price, updated_at")
       .order("updated_at, name")

根据官方文档SELECT DISTINCT ON ( expression [, ...] )

keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. For example:

SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
ORDER BY location, time DESC;

retrieves the most recent weather report for each location. But if we had not used ORDER BY to force descending order of time values for each location, we'd have gotten a report from an unpredictable time for each location.

关于ruby-on-rails - 无法在 Rails 中使用 ActiveRecord 和 PostgreSQL 从每个组中选择不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987451/

相关文章:

ruby-on-rails - 带响应的异步 Rails 操作

ruby-on-rails - 如何使用 simple_form 在错误输入中添加 "error"类?

ruby-on-rails - ActiveRecord 事务只是到数据库的 1 次往返吗?

ruby - 如何使用 `business_time` gem 获取一个月的最后一个工作日

java - 如何让 Jpa.unsafe 对 postgresql 中的 json 字段进行排序

ruby-on-rails - Rails 3 路由

ruby-on-rails - 如何使用 Rails Clockwork gem 运行 rake 任务?

ruby-on-rails - minitest 测试框架如何在 Rails 中工作?

postgresql - GIN索引怎么了,绕不开SEQ扫描?

sql - 如何通过一个请求计算玩家的多个排名?