Reputation: 10375
I have a scenario like below in SQLite: Some items which their prices during time is stored inside price table. Current prices for an item is the one which:
So how can I join below tables in SQLite such that I get a list of items with their current prices?
Besides, having several joins, will it cause too much performance degrade?
Upvotes: 0
Views: 339
Reputation: 180060
To get the row with the largest ID, use a correlated subquery which orders by the ID, and take just the first returned row:
SELECT name,
(SELECT price
FROM Table2
WHERE fkItemID = Table1.id
ORDER BY id DESC
LIMIT 1
) AS current_price
FROM Table1
This query is efficient if there is an index that allows searching on fkItemID
and then sorting on id
:
CREATE INDEX Table2_fkItemID_id ON Table2(fkItemID, id);
(If there aren't many historical prices, it is not really necessary to index the id
column.)
Upvotes: 2