i am trying to get the last rows where rec_p_id = 4 SORTED by the timestamp. Since i do not want to have all the results WHERE rec_p_id = 4, i am using GROUP BY to group it by send_p_id.
My SQL query looks like this:
SELECT *
FROM
( SELECT *
FROM chat
WHERE rec_p_id= "4"
ORDER
BY timestamp DESC) as sub
GROUP
BY send_p_id
My table looks like this:
Table chat
c_id | send_p_id | rec_p_id | timestamp |
---|---|---|---|
1 | 3 | 4 | 2020-05-01 14:46:00 |
2 | 3 | 4 | 2020-05-01 14:49:00 |
3 | 3 | 4 | 2020-05-01 14:50:00 |
4 | 7 | 4 | 2020-05-01 12:00:00 |
5 | 4 | 7 | 2020-05-01 12:10:00 |
6 | 7 | 4 | 2020-05-01 12:20:00 |
7 | 9 | 4 | 2020-05-01 16:50:00 |
8 | 9 | 4 | 2020-05-01 17:00:00 |
I want to get the last occurrences:
c_id | send_p_id | rec_p_id | timestamp |
---|---|---|---|
3 | 3 | 4 | 2020-05-01 14:50:00 |
6 | 7 | 4 | 2020-05-01 12:20:00 |
8 | 9 | 4 | 2020-05-01 17:00:00 |
But instead i get all the first ones:
c_id | send_p_id | rec_p_id | timestamp |
---|---|---|---|
1 | 3 | 4 | 2020-05-01 14:46:00 |
4 | 7 | 4 | 2020-05-01 12:00:00 |
7 | 9 | 4 | 2020-05-01 16:50:00 |
I saw the query i am using in this question: ORDER BY date and time BEFORE GROUP BY name in mysql
it seems to work for all of them. What am i doing wrong with my query? Thanks in advance.