I have the following query, which correctly returns the user ID and two other pieces of information for a certain user just before a specific timestamp ('ta.Timestamp'). There are multiple rows for the same user before and after that, and I only want that specific one.
This works perfectly for a single user, but I can't seem to find a quick and efficient way to obtain the same results for groups of users (let's say all user IDs between X and Y). I am currently running it in a loop on Python but it is way too slow for 70k+ queries.
SELECT
rm.userId,
rm.info1,
rm.info2
FROM request_metadata rm
LEFT JOIN
(SELECT userId, Timestamp
FROM table_approval
WHERE userId = {}
LIMIT 1) ta
ON rm.userId = ta.userId
WHERE rm.userId = {}
AND ta.Timestamp > rm.Timestamp
ORDER BY rm.itemId DESC
LIMIT 1;
I have tried different approaches (such as removing LIMIT and using GROUP BY), but I was not successful.
Any help is appreciated!