【发布时间】:2017-02-05 02:41:24
【问题描述】:
我想对特定用户从 ejabberd 存档表中聊天的每个用户的最后消息进行排序。
我使用的字段是这些
-
id(消息 ID) -
username(用户名复制) -
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 |
【问题讨论】:
-
您的 created_at 列是否设置为日期时间数据类型?
-
由于您的示例输出中的所有
bare_peer都是唯一的,因此它似乎正确地遵循了您的查询。您的意思是按username分组吗? -
显示输入数据和预期输出会有所帮助。也许创建一个 sql fiddle
-
输出是正确的,但它给了我最旧的消息,我需要的是最新的。
-
使用
GROUP BY无法实现您的目标,因为GROUP BY做了其他事情。它不从数据库返回行,而是使用从数据库中提取的数据生成新行。您发布的查询不是有效的 SQL。两个(或更多)具有相同bare_peer值的不同行位于同一组中。它们对id有不同的值,但您想要SELECT id。什么id?