我正在尝试根据一组发件人的时间戳返回最新消息。
基本表和 qry 看起来像这样
SELECT senderName, messages
FROM MessageTable
WHERE receiverID = 1
(output)
Joe "Hey"
Bob "Yo"
Jim "Blah"
Joe "What's up"
我想从每个发件人那里获取最新消息。我想使用 ORDER BY 和 LIMIT 但它只从整个 qry 返回 1 条消息。这不是我正在寻找的结果。
SELECT senderName, messages
FROM MessageTable
WHERE receiverID = 1
ORDER BY sentDate ASC LIMIT 1
(output)
Bob "Yo"
我希望有这种输出,其中仅返回 Joe 的最新消息以及其他发件人的最新消息。
Bob "Yo"
Jim "Blah"
Joe "What's up"
我看过 stackoverflow 上的另一个问题,但这对我来说没有意义。
https: //stackoverflow.com/questions/384142/how-to-get-latest-record-for-each-day-when-there-are-multiple-entries-per-day
谢谢!
I am trying to return back the latest message based on timestamp from a group of Senders.
The basic table and qry looks like this
SELECT senderName, messages
FROM MessageTable
WHERE receiverID = 1
(output)
Joe "Hey"
Bob "Yo"
Jim "Blah"
Joe "What's up"
I want to get the latest message from EACH sender. I thought to use ORDER BY and LIMIT but it just returns 1 message from the entire qry. Which is not the result I’m looking for.
SELECT senderName, messages
FROM MessageTable
WHERE receiverID = 1
ORDER BY sentDate ASC LIMIT 1
(output)
Bob "Yo"
I would like to have this kind of output, where only Joe's latest message is returned along with the other Sender's latest message.
Bob "Yo"
Jim "Blah"
Joe "What's up"
I've looked at another question on stackoverflow, but it didn't make sense to me.
https://stackoverflow.com/questions/384142/how-to-get-latest-record-for-each-day-when-there-are-multiple-entries-per-day
Thank you!
发布评论
评论(3)
GROUP BY 是你的朋友http://dev.mysql。 com/doc/refman/5.0/en/group-by-modifiers.html
你可以做这样的事情:
GROUP BY is your friend http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html
You could do some thing like this:
好的,经过一些搜索和反复试验,这个查询返回了我正在寻找的内容:
所有功劳都归于这个网站:http://forums.devarticles.com/general-sql-development-47/select-max-datetime-problem-10210.html
Ok, after some searching and trial and error, this query returned what i was looking for:
All the credit goes to this site: http://forums.devarticles.com/general-sql-development-47/select-max-datetime-problem-10210.html
查询的类型称为“排名查询”,它们通常需要一定程度的能力。 是一个类似的问题: 检索每个组中的最后一条记录
这 如果您使用数字 ID 而不是字符串来操作以使查询足够高效,那就更好了。
The type of the queries is called "Ranking queries" and they do usually require some level of competence. Here is a similar question: Retrieving the last record in each group
It is better if you would operate with numeric ids instead of strings to make the query efficient enough.