0

This is my database for messages enter image description here

I want to group by receiver_id and this is my SQL

SELECT * FROM messages WHERE sender_id=2
ORDER BY created_at DESC 
GROUP BY receiver_id 
HAVING COUNT(receiver_id)>=1

It's working but it always shows subject Bok and created_at=2013-08-19 20:49:22 I would like to show latest created_at and subject, in this example 2013-08-20 14:29:41

This is my output

enter image description here

zkanoca
  • 9,664
  • 9
  • 50
  • 94
FosAvance
  • 2,363
  • 9
  • 36
  • 52

2 Answers2

0
SELECT 
         m1.* 
FROM 
         messages m1 
LEFT JOIN 
         messages m2
ON 
    (m1.receiver_id = m2.receiver_id 
     AND m1.created_at < m2.created_at)
WHERE 
    m2.created_id IS NULL;
zkanoca
  • 9,664
  • 9
  • 50
  • 94
0

Groupwise maximum has helped me http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html So my query looks like

...WHERE created_at=(SELECT MAX(created_at) as created_at FROM mg_messages t2 WHERE t.receiver_id=t2.receiver_id)...

FosAvance
  • 2,363
  • 9
  • 36
  • 52