【发布时间】:2016-05-24 00:40:24
【问题描述】:
我需要获取“10 种最受欢迎”产品的列表。我认为最好的方法是使用引用Products 的Orders 表(模型)。
我知道我应该做什么,但我不知道怎么写。这就是我在 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 FROMproducts` INNER JOINordersONorders.product_id=products.idGROUP BY orders.product_id ORDER BY count desc`
标签: ruby-on-rails ruby-on-rails-4