关于sql:mysql:按用户获取最后的会话记录

mysql: Get last conversation records by user

本问题已经有最佳答案,请猛点这里访问。

我需要通过to_user以降序获取最后的会话记录。
我有一个叫做消息的表。 请看下面的截图:
enter image description here

我希望以下列方式输出:

1
2
3
 from_user| to_user | message         |
  241     |  226    |   How are you?  |
  241     |  256    | Hi test message |

我试过这个查询:

1
SELECT * FROM `messages` where from_user=241 group by to_user order by created DESC

我得到以下输出错误:

enter image description here

提前致谢。


试试他的:

1
2
3
4
5
6
7
8
9
10
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
3
4
5
6
7
SELECT *
FROM
  (SELECT *
   FROM `messages`
   WHERE from_user=241
   ORDER BY created DESC) as test
GROUP BY to_user


如果你想在一个字段中发布from_user的所有帖子(误解了我认为的问题):

1
2
3
4
5
SELECT group_concat(messages.message)
    FROM messages
    WHERE from_user = 241
    GROUP BY to_user
    ORDER BY MAX(id) DESC

您必须说明您希望订购哪种标准。 您可以开始对话或对话的最后一条消息。


试试这个

1
SELECT * FROM `messages` where from_user=241 group by to_user order by id , created DESC