Jackson
Jackson

Reputation: 1526

MySQL: Multiple Group By With Desc Order Issue

I already visited MySQL order by before group by for Single Group By it's working fine. I have issue with 2 group by columns.

I have below table named "messages". Messages are comments of User's Posts

id | posts_id | from_user_id | to_user_id | message_description | created_at
-----------------------------------------------------------------------------
1      1           1              2             test1             2016-09-06 10:00:00
2      1           1              2             test2             2016-09-06 11:00:00
3      1           4              2             test3             2016-09-06 09:00:00
4      1           4              2             test4             2016-09-06 15:00:00
5      2           1              2             test1             2016-09-06 10:00:00
6      2           1              2             test2             2016-09-06 11:00:00
7      2           4              2             test3             2016-09-06 09:00:00
8      2           4              2             test4             2016-09-06 15:00:00

Query's Result Output Should Be

id | posts_id | from_user_id | to_user_id | message_description | created_at
-----------------------------------------------------------------------------
2      1           1              2             test2             2016-09-06 11:00:00
4      1           4              2             test4             2016-09-06 15:00:00
6      2           1              2             test2             2016-09-06 11:00:00
8      2           4              2             test4             2016-09-06 15:00:00

What i'm trying to retrieve post wise & user wise their latest messages.

I gave tried below, but it's not giving result in correct order.

SELECT *
FROM messages
WHERE to_user_id = '2'
GROUP BY posts_id DESC,
         from_user_id
ORDER BY id DESC

Upvotes: 0

Views: 590

Answers (1)

Strawberry
Strawberry

Reputation: 33935

This problem is identical to thousands of others posted on SO. An optimal solution, as discussed in the manual, is an uncorellated subquery, e.g.:

SELECT x.* 
  FROM my_table x 
  JOIN 
     ( SELECT MAX(id) id 
         FROM my_table 
        WHERE to_user_id = 2 -- OPTIONAL
        GROUP 
           BY from_user_id
     ) y 
    ON y.id = x.id;

Upvotes: 1

Related Questions