0

I'm doing a group of record with the same post_id and sender id, I want each group to return record with the lastest time, I'm using myql version 5, how do I do it.

This is my messages table

enter image description here

expected results:

enter image description here

I used the following query but it did not return the record with the lastest time in each group as my expectation

select * from `messages` group by `post_id`, `sender_id` order by `time` desc
Dharman
  • 30,962
  • 25
  • 85
  • 135
Egan N
  • 105
  • 1
  • 1
  • 8

1 Answers1

0

One method uses a correlated subquery:

select m.*
from messages m
where m.time = (select max(m2.time)
                from messages m2
                where (m2.post_id, m2.sender_id) in ( (m.post_id, m.sender_id), (m.sender_id, m.post_id))
               );
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786