Reputation: 597
I have a table for a chat.
I want to get a query with the latest messages group by the conversation. (For example if the 'senderID = 1 and the recipentID = 2' that is the same conversation as 'senderID = 2 and the recipentID = 1')
Upvotes: 1
Views: 240
Reputation: 28834
ON
(explicit) and WHERE
(kind of implicit join))Try the following query:
SELECT
CONCAT(LEAST(t1.senderID, t1.recipentID),
'-',
GREATEST(t1.senderID, t1.recipentID)) AS t1_conversation,
t1.*
FROM chat_table AS t1
JOIN (
SELECT CONCAT(LEAST(t2.senderID, t2.recipentID), '-',
GREATEST(t2.senderID, t2.recipentID)) AS conversation,
MAX(t2.date) as last_message_date
FROM chat_table AS t2
GROUP BY t2.conversation
) AS t3 ON t3.max_date = t1.date
WHERE t1_conversation = t3.conversation
Upvotes: 1
Reputation: 1269443
You can use in
. MySQL supports tuples with in
, so here is one method:
select c.*
from chats c
where (least(senderID, recipentID), greatest(senderID, recipentID), date) in
(select least(senderID, recipentID), greatest(senderID, recipentID), max(date)
from chats c
group by least(senderID, recipentID), greatest(senderID, recipentID)
);
Upvotes: 2