I have a messages table as follows:
Basically what I want is, I want to fetch n
users who sent the most recent messages to a group. So it has to be grouped by from_user_id
and sorted by id
in descending order. I have the following query:
SELECT `users`.`id` AS `user_id`, `users`.`username`, `users`.`image`
FROM `group_messages`
JOIN `users` ON `users`.`id` = `group_messages`.`from_user_id`
WHERE `group_messages`.`to_group_id` = 31
GROUP BY `users`.`id`
ORDER BY `group_messages`.`id` DESC;
The problem with this is, when I group by user.id
, the row with the smallest id
field is taken into account. Therefor what I get is not in the order which id
is descending.
So is there a way to group by, taking the greatest id
into account ? Or should I approach it another way ?
Thanks in advance.
Edit: I think I got it.
SELECT `x`.`id`, `users`.`id` AS `user_id`, `users`.`username`, `users`.`image`
FROM (SELECT * FROM `group_messages` ORDER BY `group_messages`.`id` DESC) `x`
JOIN `users` ON `users`.`id` = `x`.`from_user_id`
WHERE `x`.`to_group_id` = 31
GROUP BY `users`.`id`
ORDER BY `x`.`id` DESC;
Just had to make a select from an already ordered list.