I have a table with multiple snapshots of analytics data for multiple stories. The data is stored along with the timestamp it was taken, and the story_id the data is referring to.
id: integer auto_increment
story_id: string
timestamp: datetime
value: number
and I need to pull out the latest value for each story (i.e. each unique storyId) in a list of ids.
I've written a query, but it scales catastrophically.
SELECT story_id, value
FROM table
WHERE story_id IN ('1','2','3')
AND id = (SELECT id
FROM table inner
WHERE inner.story_id = table.story_id
ORDER BY timestamp DESC
LIMIT 1)
What's a more efficient way to make this query?
Nice to know:
- story_id has to be a string, it's from an external data source
- story_id and timestamp already have indexes
- there are 2.9M rows and counting...