消息表
id (int)
recipient_id (int)
sender_id (int)
content (text)
created (datetime)
我尝试做的是从用户与其他用户进行的每次对话中获取最新消息。
让我们说我试图为user_id = 3找到它们,这就是我到目前为止所做的。它不是一个很好的解决方案,感觉有点像黑客,但它正在发挥作用。
SELECT *
FROM messages
WHERE id IN
(SELECT MAX(id) FROM messages
WHERE `recipient_id` = 3 OR `sender_id` = 3
GROUP BY (recipient_id + sender_id))
ORDER BY created DESC
答案 0 :(得分:0)
使用GROUP BY recipient_id,sender_id。
SELECT *
FROM messages
WHERE id IN
(SELECT MAX(id) FROM messages
WHERE `recipient_id` = 3 OR `sender_id` = 3
GROUP BY recipient_id, sender_id)
ORDER BY created DESC
答案 1 :(得分:0)
首先让我清楚你的问题?
看到你的查询后我建议你用这个
SELECT * FROM messages WHERE `recipient_id` = 3 OR `sender_id` = 3
GROUP BY (recipient_id + sender_id)) ORDER BY created DESC limit 1
它会为您提供最新消息
我根据你的问题给出限制1的原因是什么? 最新,但如果您需要从最新消息中获取所有消息,请先从该查询中删除limit 1