-4

我有一个这样的 SQL 查询:

select * 
from orders 
where order_session_id IN ( 
   select id order_status 
   from order_sessions 
   where order_status IN (
      select id 
      from order_status_types 
      where order_status != "Paid"
   )
)

这返回了一个哈希。我用 ruby​​ 编写了它,但我觉得它可以优化。

@orders = []
paid_order_status_id = OrderStatusType.find_by_order_status("Paid").id
OrderSession.where('order_status != ?',paid_order_status_id).each { |unpaid_order|
  @orders << Order.find(unpaid_order.id)
}
4

1 回答 1

2

假设您有以下关联

OrderSession belongs_to Order
Order has_one OrderSession

你试试

@orders = Order.joins(:order_session).where('order_sessions.order_status != ?', paid_order_status_id)
于 2013-03-12T14:41:21.900 回答