【发布时间】:2011-12-29 04:54:06
【问题描述】:
我有一个名为 ORDEREXECUTIONS 的表,其中存储了所有已执行的订单。这是一个多币种应用程序,因此该表有两列 CURRENCY1_ID 和 CURRENCY2_ID。
要获取特定货币对(例如欧元/美元)的所有订单列表,我需要逐行获取总数:
v = Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",c1,c2,Time.now()-24.hours).sum("quantity").to_d
v+= Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",c2,c1,Time.now()-24.hours).sum("unitprice*quantity").to_d
请注意,我的 SUM() 公式因货币顺序而异。 例如如果我想要货币对 USD 的总订购数量,则它会执行(假设 USD 的货币 ID 为 1,EUR 为 2。
v = Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",1,2,Time.now()-24.hours).sum("quantity").to_d
v+= Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",2,1,Time.now()-24.hours).sum("unitprice*quantity").to_d
如何在 RoR 中编写它,以便它只触发一条 SQL 语句到 MySQL?
【问题讨论】:
-
2次查询中条件中c1,c2的顺序是不是故意的?
-
是的,这是故意的。我不是将数据存储在数据库中的方式。 currency1_id 始终是买入货币,currency2_id 是卖出货币。我在一张桌子上存储买卖。
标签: mysql ruby-on-rails-3 performance