all! I have the following problem: I have 2 simple tables. The first one, say, “currency”, stores the information about the currencies (ISO 4217 code (PK), name, etc.). The second one, “rates”, has the following fields: id, currency_code (references currency.code), date_added (datetime), rate.
What I want to fo is to select the latest exchange rates for several currency codes. First, I wanted to do it like this:
SELECT r.rate
FROM rates r
WHERE r.id IN (SELECT id
FROM rates r1
WHERE r1.currency_code IN('USD', 'EUR')
GROUP BY r1.currency_code
ORDER BY r1.date_added DESC)
ORDER BY r.currency_code ASC
but I soon remembered that the ORDER clause will be taken into account after the results are grouped. In my case, the subquery ended up returning the ids of the earliest rates…
I suppose I could get the rates for each currency code separately, but I still hope that I’ll be able to use a single clean query.
Assuming that the latest exchange rate is the one with the highest id you can use:
But I strongly suggest another pattern I love. I explained it in another answer this morning: