0

Is there any better way (performance wise) to link transactions with currency exchange table where the transaction table has more than a million records ?

tabTran

date amount currency
2023-01-01 100 GBP
2023-01-05 200 INR
2023-01-07 150 EUR
2023-01-13 50 INR
2023-01-15 100 GBP

tabCurrency_Exchange

date from_curr to_curr exch_rate
2022-12-25 AED USD 0.276495000
2022-12-28 AED USD 0.276495000
2022-12-28 PLN USD 0.226435000
2022-12-30 EUR USD 1.170000000
2023-01-02 AED USD 0.277130000
2023-01-02 PLN USD 0.228550000
2023-01-05 PLN USD 0.228550000
2023-01-05 EUR USD 0.971758000
2023-01-06 EUR USD 1.089531680
2023-01-10 PLN USD 1.089531680
2023-01-10 EUR USD 0.235714280
2023-01-14 AED USD 0.272521000
2023-01-15 AED USD 0.276495000
2023-01-15 PLN USD 0.228571400
CREATE TEMPORARY TABLE IF NOT EXISTS tabTran ENGINE=MEMORY  AS (
    SELECT '2023-01-01' `date`, 100 amount, 'AED' currency
    UNION SELECT '2023-01-05', 200, 'PLN'
    UNION SELECT '2023-01-07', 159, 'EUR'
    UNION SELECT '2023-01-13', 50, 'PLN'
    UNION SELECT '2023-01-15', 100, 'AED'
);
    
CREATE TEMPORARY TABLE IF NOT EXISTS tabCurrency_Exchange ENGINE=MEMORY  AS (
    SELECT '2022-12-25' `date`, 'AED' from_curr, 'USD' to_curr, 0.276495000 exch_rate
    UNION SELECT '2022-12-28', 'AED', 'USD', 0.276495000 
    UNION SELECT '2022-12-28', 'PLN', 'USD', 0.226435000 
    UNION SELECT '2022-12-30', 'EUR', 'USD', 1.170000000 
    UNION SELECT '2023-01-02', 'AED', 'USD', 0.277130000 
    UNION SELECT '2023-01-02', 'PLN', 'USD', 0.228550000 
    UNION SELECT '2023-01-05', 'PLN', 'USD', 0.228550000 
    UNION SELECT '2023-01-05', 'EUR', 'USD', 0.971758000 
    UNION SELECT '2023-01-06', 'EUR', 'USD', 1.089531680 
    UNION SELECT '2023-01-10', 'PLN', 'USD', 1.089531680 
    UNION SELECT '2023-01-10', 'EUR', 'USD', 0.235714280 
    UNION SELECT '2023-01-14', 'AED', 'USD', 0.272521000 
    UNION SELECT '2023-01-15', 'AED', 'USD', 0.276495000 
    UNION SELECT '2023-01-15', 'PLN', 'USD', 0.228571400 
);
    

expected result

date amount currency to_curr exch_rate
2023-01-01 100 AED USD 0.276495000
2023-01-05 200 PLN USD 0.228550000
2023-01-07 150 EUR USD 1.089531680
2023-01-13 50 PLN USD 1.089531680
2023-01-15 100 AED USD 0.276495000

what I tried

select `date`, amount, currency, 'USD' to_curr, 
(
    select exch_rate from tabCurrency_Exchange where 
    from_curr = tabTran.currency
    and to_curr = 'USD'
    and `date` <= tabTran.date
    order by `date` desc
    limit 1
) exch_rate
from tabTran;

checked previous posts Multiple Currency Conversions in Single Query Select Exchange Rate based on Currency and Date How to join most recent currency exchange date on a date which falls on a weekend or holiday? Joining Exchange rate with a currency table

0 Answers0