mysql - 从每个组中获取最新记录

标签 mysql sorting group-by

我想对特定用户从 ejabberd 存档表聊天的每个用户的最后消息进行排序。

我正在使用的字段是这些

  • id(消息 ID)
  • 用户名(用户名副本)
  • bare_peer(正在聊天的用户)
  • txt(文字聊天)
  • created_at(创建时间)

我想要实现的是类似的东西,但我需要通过 bare_peer 将消息分组,用户名为 1_usernode,但仅限于最后的消息。

我已经测试了很多查询,但没有一个有效。 这是我尝试的第一个查询。

SELECT id, username, bare_peer, txt FROM archive where
username = '1_usernode' GROUP BY bare_peer ORDER BY created_at DESC;

这是输出。

+------+------------+-------------------------------------------------------+---------------------+
| id   | username   | bare_peer              | txt                          | created_at          |
+------+------------+------------------------+------------------------------+---------------------+
| 1095 | 1_usernode | 10_usernode@localhost  | Hello !!!                    | 2016-07-17 21:15:17 |
| 1034 | 1_usernode | 15_usernode@localhost  | hey sup ?                    | 2016-07-13 22:40:29 |
| 1107 | 1_usernode | 13_usernode@localhost  | oi                           | 2016-07-18 00:09:28 |
| 1078 | 1_usernode | 2_usernode@localhost   | Hello this is just a Test!!! | 2016-07-15 16:30:50 |
| 1101 | 1_usernode | 7_usernode@localhost   | hey                          | 2016-07-18 00:05:55 |
| 1084 | 1_usernode | 3_usernode@localhost   | Hey how are you?             | 2016-07-15 19:36:44 |
| 1085 | 1_usernode | 4_usernode@localhost   | Hey how are you doing ?      | 2016-07-17 19:20:00 |

最佳答案

使用这个查询很有帮助。

SELECT MAX(id), username, bare_peer, txt FROM archive where
username = '1_usernode' ORDER BY created_at DESC

关于mysql - 从每个组中获取最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725113/

相关文章:

php - Phalcon 模型更新不起作用

java - 比较器返回类型与整数不兼容

python - 如果不满足条件,则删除组中的所有行

javascript - 排序方法的javascript函数中的value1和value 2是什么

java - 在 Elastic Search 中设置动态日期格式

MYSQL 返回使用 group by 进行比较的日期输出

MySQL 根据两列查找记录与前一天的差异

mysql - "Secondary"查询

php - 在数据库的帮助下在 PHP 中创建一个计数器?

php - 如何显示数据库中的 BLOB 图像?