如何在rails active record style
中编写此查询SELECT COUNT(o.id) no_of_orders,
SUM(o.total) total,
SUM(o.shipping) shipping
FROM orders o JOIN
(
SELECT DISTINCT order_id
FROM designer_orders
WHERE state IN('pending', 'dispatched', 'completed')
) d
ON o.id = d.order_id
答案 0 :(得分:7)
您可以使用显式查询,您有两种方式来执行此操作:
Model.where("MYSQL_QUERY")
或
Model.find_by_sql("MYSQL_QUERY")
http://apidock.com/rails/ActiveRecord/Base/find_by_sql/class
OR
在Rails样式中有更多步骤(可能用更少的步骤完成):
order_ids = DesignerOrder.where("state IN (?)", ['pending', 'dispatched', 'completed']).select(:order_id).distinct
partial_result = Order.where("id IN (?)", order_ids)
no_of_orders = partial_result.count
total_sum = partial_result.sum(:total)
shipping_sum = partial_result.sum(:shipping)
答案 1 :(得分:5)
您也可以这样做
Order
.select('
COUNT(o.id) no_of_orders,
SUM(o.total) total,
SUM(o.shipping) shipping
')
.from('orders o')
.joins("
(#{
DesignerOrders
.select("DISTINCT order_id")
.where("state IN('pending', 'dispatched', 'completed')")
}) d on o.id = d.order_id
")
我实际上没有运行它,但这个概念是有效的。如果使用“from”,则甚至不需要活动记录模型。我们使用这样的技术为非常复杂的SQL做AR样式查询,这让我们的生活变得更加轻松。