-
-
Save afsunday/24474ff0efb4b3c83cd3e7584de3c17f to your computer and use it in GitHub Desktop.
Get latest conversation with last message per user. (MySQL query)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| SELECT | |
| * | |
| FROM | |
| messages, | |
| ( | |
| SELECT | |
| MAX(id) as lastid | |
| FROM | |
| messages | |
| WHERE | |
| ( | |
| messages.to_id = 1 -- ID to compare with (logged in users's ID) | |
| OR messages.from_id = 1 -- ID to compare with (logged in users's ID) | |
| ) | |
| GROUP BY | |
| CONCAT( | |
| LEAST(messages.to_id, messages.from_id), | |
| '.', | |
| GREATEST(messages.to_id, messages.from_id) | |
| ) | |
| ) as conversations | |
| WHERE | |
| id = conversations.lastid | |
| ORDER BY | |
| messages.created_at DESC | |
| /* Another way using join */ | |
| SELECT | |
| * | |
| FROM messages m | |
| INNER JOIN | |
| ( | |
| SELECT MAX(id) as lastid | |
| FROM messages | |
| WHERE | |
| ( | |
| messages.to = 1 -- ID to compare with (logged in users's ID) | |
| OR | |
| messages.from_id = 1 -- ID to compare with (logged in users's ID) | |
| ) | |
| GROUP BY | |
| CONCAT( | |
| LEAST(messages.to_id, messages.from_id), | |
| '.', | |
| GREATEST(messages.to_id, messages.from_id) | |
| ) | |
| ) conversations | |
| ON conversations.lastid = m.id | |
| ORDER BY | |
| m.created_at DESC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment