我正在尝试根据来自一组发件人的时间戳返回最新消息。
基本表和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的最新消息与其他Sender的最新消息一起返回。
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
谢谢!
答案 0 :(得分:0)
GROUP BY是您的朋友http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html
你可以这样做:
SELECT senderName, messages
FROM MessageTable
GROUP BY senderName
ORDER BY sentDate DESC
答案 1 :(得分:0)
好的,经过一些搜索和反复试验后,此查询返回了我要查找的内容:
SELECT a.senderName, a.messages, a.sentDate
FROM MessageTable AS a,
(
SELECT senderName, MAX(sentDate) as max_date
FROM MessageTable
WHERE ReceiverID = 1
GROUP BY senderName
) AS b
WHERE a.senderName = b.senderName
AND a.sentDate = b.max_date;
所有功劳都归功于此网站:http://forums.devarticles.com/general-sql-development-47/select-max-datetime-problem-10210.html
答案 2 :(得分:0)
查询的类型称为“排名查询”,它们通常需要一定程度的能力。这是一个类似的问题:Retrieving the last record in each group
最好使用数字ID而不是字符串来使查询足够有效。