我需要通过to_user以降序获取最后的会话记录。 我有一个叫做消息的表。请看下面的截图:
我希望以下列方式输出:
from_user| to_user | message |
241 | 226 | How are you? |
241 | 256 | Hi test message |
我试过这个问题:
SELECT * FROM `messages` where from_user=241 group by to_user order by created DESC
我收到以下输出错误:
提前致谢。
答案 0 :(得分:4)
试试他的:
SELECT t1.*
FROM `messages` AS t1
JOIN (
SELECT to_user, MAX(created) AS created
FROM `messages`
WHERE from_user=241
GROUP BY to_user
) AS t2 ON t1.to_user = t2.to_user AND t1.created = t2.created
WHERE from_user=241
ORDER BY t1.created DESC
答案 1 :(得分:2)
SELECT *
FROM
(SELECT *
FROM `messages`
WHERE from_user=241
ORDER BY created DESC) as test
GROUP BY to_user
答案 2 :(得分:1)
试试这个
SELECT * FROM `messages` where from_user=241 group by to_user order by id , created DESC
答案 3 :(得分:1)
如果你想在一个字段中发布from_user的所有帖子(误解了我认为的问题):
SELECT group_concat(messages.message)
FROM messages
WHERE from_user = 241
GROUP BY to_user
ORDER BY MAX(id) DESC
您必须说明您希望订购哪种标准。您可以开始对话或对话的最后一条消息。