Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL select GROUP BY order

I have a mysql statement

SELECT * 
FROM tbl_messages 
WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' 
GROUP BY from_user_id 
ORDER BY date_sent DESC

and it is producing the correct results however they are not in the correct order.

The grouping works well but it record displayed in the group is the first recorded entered into the DB but I would like the latest record to be displayed in each group.

Is there a way to have the latest record displayed for each group?

2011-12-19 12:16:25 This is the first message
2011-12-19 12:18:20 This is the second message
2011-12-19 12:43:04 This is the third message

The group shows 'This is the first message' where I would like 'This is the third message' as that is the most recent record/message.

Cheers

like image 564
puks1978 Avatar asked Dec 19 '11 01:12

puks1978


1 Answers

This may work (but not guaranteed):

SELECT * 
FROM
  ( SELECT *
    FROM tbl_messages 
    WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' 
    ORDER BY date_sent DESC
  ) tmp
GROUP BY from_user_id 
ORDER BY date_sent DESC

This should work:

SELECT t.* 
FROM 
    tbl_messages AS t
  JOIN
    ( SELECT from_user_id 
           , MAX(date_sent) AS max_date_sent
      FROM tbl_messages 
      WHERE to_user_id = '$user_id' OR from_user_id = '$user_id' 
      GROUP BY from_user_id 
    ) AS tg
    ON  (tg.from_user_id, tg.max_date_sent) = (t.from_user_id, t.date_sent)
ORDER BY t.date_sent DESC
like image 60
ypercubeᵀᴹ Avatar answered Oct 08 '22 23:10

ypercubeᵀᴹ