MySQL 选择 GROUP BY 顺序
我有一个 mysql 语句
SELECT *
FROM tbl_messages
WHERE to_user_id = '$user_id' OR from_user_id = '$user_id'
GROUP BY from_user_id
ORDER BY date_sent DESC
,它产生了正确的结果,但它们的顺序不正确。
分组效果很好,但组中显示的记录是输入数据库的第一个记录,但我希望在每个组中显示最新记录。
有没有办法让每个组显示最新的记录?
2011-12-19 12:16:25 This is the first message
2011-12-19 12:18:20 This is the second message
2011-12-19 12:43:04 This is the third message
该组显示“这是第一条消息”,我希望“这是第三条消息”,因为这是最新的记录/消息。
干杯
I have a mysql statement
SELECT *
FROM tbl_messages
WHERE to_user_id = '$user_id' OR from_user_id = '$user_id'
GROUP BY from_user_id
ORDER BY date_sent DESC
and it is producing the correct results however they are not in the correct order.
The grouping works well but it record displayed in the group is the first recorded entered into the DB but I would like the latest record to be displayed in each group.
Is there a way to have the latest record displayed for each group?
2011-12-19 12:16:25 This is the first message
2011-12-19 12:18:20 This is the second message
2011-12-19 12:43:04 This is the third message
The group shows 'This is the first message' where I would like 'This is the third message' as that is the most recent record/message.
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可能有效(但不能保证):
这应该有效:
This may work (but not guaranteed):
This should work:
通过使用 GROUP BY 包装查询,在 ORDER BY 之后执行 GROUP BY,如下所示:
Do a GROUP BY after the ORDER BY by wrapping your query with the GROUP BY like this:
如果您的消息表有一个自动递增的主键,并且所有消息本质上最大的数字是最近的日期...但是,因为我不知道这一点,所以我将基于 MAX( date_sent )而不是 max( SomeIDKey ),但原理是一样的。
If your messages table has a primary key that is auto-increment, and all messages are by nature highest number is the most recent date... However, since I don't KNOW that, I am going based on the MAX( date_sent ) instead of max( SomeIDKey ), but the principle is the same.
你的意思是这样的吗:
Do you mean something like this: