I'm using two tables in the database:
The "members" table:
id | name
-----------------------
1 | John
2 | Mike
3 | Jane
4 | Marry
The "messages" table:
message_id | text | from | to
---------------------------------------------
1 | text 1 | 1 | 2
2 | text 2 | 1 | 3
3 | text 3 | 1 | 4
4 | text 4 | 2 | 1
5 | text 5 | 1 | 2
I need to get as a result grouped messages sent by a specific user, sorted by the last message sent and count the total number of sent messages to specific user.
My current mysql query looks:
SELECT max(messages.message_id) as max_mess, messages.from, messages.to, members.name, messages.text
FROM messages INNER JOIN members on members.id = messages.to
WHERE messages.from = '1'
GROUP BY messages.from
ORDER BY max_mess DESC
Required result should look like:
max_mess | from | to | name | text | total_messages
--------------------------------------------------------------------
5 | 1 | 2 | Mike | text 5 | 3
3 | 1 | 4 | Marry | text 3 | 1
2 | 1 | 3 | Jane | text 2 | 1
Is it possible to do that using only one mysql query and what should be changed in the current query?