【问题标题】:Rails Select Most Popular ProductsRails 选择最受欢迎的产品
【发布时间】:2016-05-24 00:40:24
【问题描述】:

我需要获取“10 种最受欢迎​​”产品的列表。我认为最好的方法是使用引用ProductsOrders 表(模型)。

我知道我应该做什么,但我不知道怎么写。这就是我在 MySQL 中的做法:

SELECT  products.* 
FROM (SELECT product_id, count(product_id) as count from Orders 
           GROUP BY product_id
           ORDER BY count DESC
           LIMIT 10) AS O
LEFT OUTER JOIN products
ON Products.id  = O.product_id

如何在 Rails 中编写查询?

例如: Order.group(:product_id).count...

【问题讨论】:

  • 查询看起来不错,如果您将left outer join 更改为inner join,它应该只会为您提供10 个符合条件的产品。这就是你要找的吗?
  • @lusketeer 我需要用 Rails 编写...比如:Order.group(:product_id).count...
  • 试试Products.joins(:orders).select("orders.product_id, count(orders.product_id) as count").order("count desc").group("orders.product_id")
  • @Amit Badheka Pykih 员工就是我得到的:=> #<ActiveRecord::Relation [#<Product id: nil>, #<Product id: nil>, #<Product id: nil>, #<Product id: nil>, #<Product id: nil>]>。运行的查询:SELECT orders.product_id, count(orders.product_id) as count FROM products` INNER JOIN orders ON orders.product_id = products.id GROUP BY orders.product_id ORDER BY count desc`

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

试试

# One single query with join (extract the subquery and 
# assign it to an alias t using active_record function .from)
Product.joins("INNER JOIN t ON t.product_id = products.id")
       .from(
         Order
            .select("orders.product_id, COUNT(orders.id) as count")
            .group("orders.product_id").order("count DESC").limit(10), 
       :t)

# Alternative, but I think it will use 2 queries, 
# and the first one is probably faster
Product
      .where(id: 
      Order
         .select("orders.product_id, COUNT(orders.id) as count")
         .group("orders.product_id").order("count DESC").limit(10).pluck(:product_id))

更新:

该代码对我有用 (@KazKazar):

Product.joins("INNER JOIN products ON products.id = O.product_id") .from(Order.select("product_id, COUNT(product_id) as count") .group("product_id").order("count DESC").limit(10),:O)

【讨论】:

  • @KazKazar 缺少什么
  • 不确定为什么其中任何一个都不起作用,您在运行之前是否取出了空格?我把它们放在多行以便更好地阅读
猜你喜欢
  • 2021-02-20
  • 2021-07-02
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
相关资源
最近更新 更多