I have seen plenty of similar questions asked:
Most starred one is this one: Retrieving the last record in each group - MySQL
But my question is different.
I would like to select latest of a group (each option_id) for 1 user. Not all latest and not all latest for all users.
Imagine table called "options":
+-----+-----------+---------+-------+
| id | option_id | user_id | value |
+-----+-----------+---------+-------+
| 100 | 3 | 2 | 1000 |
| 99 | 3 | 2 | 500 |
| 98 | 3 | 2 | 1000 |
| 97 | 2 | 2 | 2 |
| 96 | 2 | 2 | 6 |
| 95 | 1 | 2 | 88 |
| 94 | 1 | 2 | 87 |
| 93 | 3 | 2 | 1000 |
| 92 | 2 | 1 | 85 |
+-----+-----------+---------+-------+
Expected result of the query for user_id=2:
+-----+-----------+---------+-------+
| id | option_id | user_id | value |
+-----+-----------+---------+-------+
| 100 | 3 | 2 | 1000 |
| 97 | 2 | 2 | 2 |
| 95 | 1 | 2 | 88 |
+-----+-----------+---------+-------+
Pseudo query:
select latest (highest id) of each option_id where user_id=2
This is what I tried:
SELECT *
FROM options
where user_id =2 and id IN (
select max(id)
from options
group by option_id
)
It seems like it gives expected results but only for some option_id not all. So I would get row 100 and 95 only for user_id=2, but option_id 2 is missing in results.