I have a chat app on my website. The chat messages stored in a table with timestamp.
Also I list out all users (for now it’s ordered by Username).
SELECT username
FROM accounts
WHERE NOT id = 57 AND activation_code = 'activated'
ORDER BY username ASC;
I want to order the users by the last sent messages timestamp.
I managed to create the query to show only the last sent message’s date for the logged in user (for now his id is 57).
SELECT msg_date FROM messages
WHERE outgoing_msg_id = 57
ORDER BY msg_date DESC
LIMIT 1;
How can i combine the two?
2
Answers
Test this:
I hope that there are no messages to self..
If you need in ALL users (even there is no messages from them) then try
One solution is a lateral join:
Another is using a common join with an aggregation per user:
Yet another way is a subquery in the
ORDER BY
clause:If you want to show message data along with the user account data, the lateral join is the best approach:
Or use a window function to pick the latest message per user: