I have this kind of table for simple chat:
messages table structure
+----+---------+-----------+---------+------+------+
| id | to_user | from_user | message
You are getting the last message from each user because you have done GROUP BY for both: to_user and from_user.
There is no need to use GROUP BY clause in your query.
Remove the group by
clause in your in
statement--it's useless in this case. It's returning a sent
timestamp for each distinct pairing of to_user
and from_user
. You really just want the max sent
where to_user
or from_user
equal some value. Lose the group by
, and you'll return exactly one record showing the latest message either to or from a user.
It looks like this:
SELECT *
FROM `messages`
WHERE `sent`
IN (
SELECT MAX( `sent` )
FROM `messages`
WHERE `from_user` = '1' --id of user who is requesting the list
OR `to_user` = '1' --id of user who is requesting the list
)
LIMIT 0 , 30
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.
SELECT *
FROM `messages`
WHERE `sent`
IN (
SELECT MAX( `sent` )
FROM `messages`
WHERE (`from_user` = '1' OR `to_user` = '1')
)
LIMIT 0 , 30
the groupby is going to conbine them i believe.