I have a table in mysql where it stores the messages between users. The Table has the following fields:
ID from_memberID to_memberID message Date
+----+--------------+------------+-----------------------+-----------------------+
1 205 207 hello Peter 19/08/2012 20:00:00
2 207 205 Hi frank 19/08/2012 20:01:00
3 205 208 hello Jennifer 19/08/2012 20:10:00
4 207 210 hello Peter 19/08/2012 20:20:00
Well, let's suppose I want to get only last message from each conversation by user 205
it should get registers 2 and 3, the conversation between users(205-207) and users (205-208). The fact is that i use GROUP BY from_memberID and then in my result the register ID=1 is added too.
This is the statement is use:
SELECT *
FROM
(SELECT msg.ID,
msg.mensaje,
msg.from_miembroID,
msg.fecha,
msg.read,
FROM mensajes as msg
INNER JOIN miembros as mem ON mem.ID=IF(msg.from_miembroID=205, msg.to_miembroID, msg.from_miembroID)
WHERE msg.to_miembroID=205 OR msg.from_miembroID=205
ORDER BY msg.fecha DESC) as temp
GROUP BY from_miembroID
how can i use GROUP BY for considering the two columns (from_memberID, to_memberID) to be as one?
Thanks in advance.
You could use a new custom field, ordering the ids (from_memberID
, to_memberID
) by a custom rule, e.g. the smaller one always comes first.
For example:
SELECT
IF(from_memberID < to_memberID,
CONCAT(from_memberID, '-', to_memberID),
CONCAT(to_memberID, '-', from_memberID)
) as conversation_ids
FROM `messages`
That field will return unique combinations, e.g. 205-207 no matter if 205 sent a message to 207 or 207 sent a message to 207.
Finally, you could group by this value and get unique combinations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With