MySQL:分组内排序?
所以我的 CMS 中的成员之间有这个消息数据库。我想更改列表以向人们显示而不是特定消息。称之为“线程”,但“我的消息”页面中的每个线程都是与您进行过对话的成员,对吧?
所以,我显然是用这样的东西来做的:
select id, msgfrom, headline from member.msg where msgto = $myid
group by msgfrom order by date desc
是的,但上面的问题是它显示了每个“msgfrom”的第一条消息的标题。因此,按日期排序将应用于第一条消息的日期。即我希望返回代表该组的整行遵守特定的顺序。
如果我要从数据库中获取所有文本并按类别对它们进行分组,从而显示每个类别的最后一个文本,这将是相关的。全部在一个查询中。
更糟糕的是,我还想获取对方尚未响应的消息“线程”(因此还没有 msgto = $myid,而是 msgfrom = $myid),然后分组应该打开“msgto”而不是“msgfrom”
那么,有什么想法吗?
So I have this messages database between members in my CMS. I wanted to change the listing to show people instead of specific messages. Call it "threads" but each thread in the "my messages" page is a member that you've had a conversation with, right?
So, I obviously do this with something like this:
select id, msgfrom, headline from member.msg where msgto = $myid
group by msgfrom order by date desc
Right, but the problem with the above is that it shows the headline of the FIRST message from each "msgfrom". So the ordering by date is applied to the date of that first message. I.e. I want the entire row returned that represents the group to obey a specific ordering.
This would be relevant if I was to fetch all texts from a database and group them by category and thus show the last text from each category. All in one query.
To make matters worse, I would also want to fetch message "threads" where the other party hasn't yet responded (so there is no msgto = $myid yet, but rather a msgfrom = $myid) and the grouping should then be on "msgto" instead of "msgfrom"
So, any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是每天都会出现的经典“每组最大”查询。有很多很多方法可以解决这个问题,之前已经介绍过(尝试搜索SO),但是我给你举一个例子来帮助你开始:
我不太明白你问题的后半部分。您能更详细地解释一下吗?也许可以举个例子?您希望它成为同一查询的一部分还是单独查询的一部分?
This is a classic 'max per group' query that comes up on here every day. There are many, many ways to solve it that have been covered before (try searching SO) but I'll give you one example to get you started:
I don't really understand the second half of your question. Can you explain it in more detail, perhaps with an example? Do you want this to be part of the same query or a separate query?