mysql: 按用户获取最后的对话记录

12 浏览
0 Comments

mysql: 按用户获取最后的对话记录

这个问题已有答案

检索每个组中的最后一条记录-MySQL

我需要按倒序方式按to_user获取最后的对话记录。

我有一个名为messages的表格。请查看以下截图:

\"enter

我想以以下方式输出:

 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

我得到了错误的输出:

\"enter

谢谢提前。

admin 更改状态以发布 2023年5月24日
0
0 Comments
SELECT *
FROM
  (SELECT *
   FROM `messages`
   WHERE from_user=241
   ORDER BY created DESC) as test
GROUP BY to_user

表示一个带有粗体的段落内容。

0
0 Comments

尝试这个:

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

0