I have this kind of table for simple chat:
messages table structure
+----+---------+-----------+---------+------+------+
| id | to_user | from_user | message
Here's how you do it:
SELECT *
FROM (SELECT *
FROM messages
WHERE from_user = ?
OR to_user = ?
ORDER by from_user, to_user, sent DESC
) x
GROUP BY from_user, to_user
ORDER BY sent DESC
LIMIT 1;
In mysql, a group by without aggregating the other columns returns the first row for each group. By selecting form an ordered row set (the inner query) we get the most recent row for each conversation.