I am using this query to fetch list of who messaged a user or who user messaged to.
SELECT messages.*
FROM (
SELECT MAX(lastseen) AS lastseen
FROM mess
I think this is what you're after.
SELECT messages.*
FROM
(SELECT MAX(lastseen) AS lastseen,IF ('Tom' = `from`,`to`,`from`) as otheruser FROM messages
WHERE 'Tom' IN (`from`,`to`) GROUP BY otheruser
)
AS latest INNER JOIN messages ON latest.lastseen = messages.lastseen
AND (('Tom' = messages.from AND latest.otheruser = messages.to)
OR
('Tom' = messages.to AND latest.otheruser = messages.from))
ORDER BY messages.lastseen
DESC,`read`='no' limit 10
just replace 'Tom' with your variable
This will return the latest 10 users that messaged to 'Tom' or 'Tom' messaged to.