我有一张桌子聊天。
我想通过对话获取有关最新消息组的查询。 (例如,如果'senderID = 1且recipentID = 2'与'senderID = 2且recipentID = 1'是相同的对话)
答案 0 :(得分:2)
您可以使用in
。 MySQL支持in
的元组,因此这是一种方法:
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)
);
答案 1 :(得分:1)
ON
(显式)和WHERE
(隐式连接的类型)) 尝试以下查询:
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