[英]select data where date is max(date) less than x
I have 2 tables The first one has exchange rates: 我有2张桌子第一张有汇率:
| date | ratio | currency |
------------------------------
1| 9/09 | 1.0 | EUR |
2| 9/09 | 1.1 | USD | -- no weekend
3| 12/09 | 1.0 | EUR | -- goes from 9 to 12
4| 12/09 | 120.0 | JPY |
The second one has transactions 第二个有交易
| date | amount | currency |
------------------------------
1| 9/09 | 20.0 | EUR |
2| 9/09 | 101.0 | USD | -- weekend
3| 10/09 | 1.0 | USD | -- has 10/09 which is a saturday
4| 10/09 | 10.0 | USD |
Both contain the date and the currency. 两者都包含日期和货币。 As it stands my exchange rates are not updated during the weekend, and that won't change. 就目前而言,我的汇率在周末不会更新,并且不会改变。
I'm looking for a performant way to select the last available data to be put into the exchange_rate table. 我正在寻找一种高性能的方法来选择要放入exchange_rate表中的最后一个可用数据。 In other words, the last day before the missing day.(10/09 in the example) 换句话说,就是缺少日期的最后一天。(示例中为10/09)
I'm using the transaction table to get a list of days that need the exchange-rate information, so that I can convert everything to EUR. 我正在使用交易表来获取需要汇率信息的天数列表,以便可以将所有货币转换为欧元。
the full result wanted should be something like 想要的完整结果应该是这样的
| date | amount | currency | ratio |
----------------------------------------
1| 9/09 | 20.0 | EUR | 1.0 |
2| 9/09 | 101.0 | USD | 1.1 | -- already exists in exchange_rate
3| 10/09 | 1.0 | USD | 1.1 | -- selected because 9/09 is last available line
4| 10/09 | 10.0 | USD | 1.1 |
Alternatively I am fine with a query that updates the exchange_rate table with the needed data as well, because the final query would be cleaner and easier to maintain later on 另外,我也可以使用需要的数据来更新exchange_rate表的查询,因为最终查询会更简洁,以后更易于维护
You can do this using a correlated subquery: 您可以使用相关子查询来执行此操作:
select t.*,
(select er.ratio
from exchangerates er
where er.date <= e.date and er.currency = t.currency
order by er.date desc
limit 1
) as ratio
from transactions t;
For performance, you want an index on exchangerates(currency, date, ratio)
. 为了提高性能,您需要exchangerates(currency, date, ratio)
的索引。
I would start with this and see if it meets your needs. 我将从此开始,看看它是否满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.