获取GROUP BY语句的最新文本条目

时间:2012-08-10 16:59:41

标签: mysql

我有一个数据库,用于保存邮件对话

table "conversations"
ID    SUBJECT
1     meeting on Friday

table "conversations_mails"
ID    CONVERSATION_ID    TEXT                               CREATED_ON
1     1                  "What about a meeting on Friday?"  2012-08-05 10:00:00
2     1                  "that's a good idea!"              2012-08-10 15:00:00

现在,我想显示一个对话概述页面,显示最新回复的截断文本版本。例如

"Meeting on Friday"
That's a good ... 

我尝试通过GROUP BY实现这一目标。但我得到的是表格中的第一个回复(“周五会议怎么样”),而不是最后一个“那是一个好主意”。

这是我的SQL语句:

SELECT *, MAX(conversations_mails.created_on) As conversation_last_reply,
  MAX(conversations_mails.id) AS maxId
FROM conversations 
LEFT JOIN conversations_mails ON conversations_mails.conversation_id = conversations.id 
GROUP BY conversations.id 
ORDER BY conversation_last_reply DESC

我知道如何通过MAX()获得最高ID,但相应的TEXT条目呢?

谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个 -

SELECT *, MAX(conversations_mails.created_on) As conversation_last_reply,
  MAX(conversations_mails.id) AS maxId
FROM conversations 
LEFT JOIN conversations_mails ON conversations_mails.conversation_id = conversations.id 
WHERE conversations_mails.id = (select max(conversations_mails.id) from conversations_mails where conversations_mails.conversation_id = conversations.id)
GROUP BY conversations.id 
ORDER BY conversation_last_reply DESC

答案 1 :(得分:1)

有两个选项:使用子查询(如geeky_bat建议),或添加另一个JOIN来过滤掉旧行。以下是使用另一个JOIN

的方法
SELECT 
  cm.created_on AS conversation_last_reply,
  cm.id AS maxId, 
  cm.conversation_text
FROM conversations c
  LEFT OUTER JOIN conversations_mails cm
  ON cm.conversation_id = c.id 
  LEFT OUTER JOIN conversations_mails cm_newer
  ON cm_newer.conversation_id = c.id
  AND cm_newer.created_on > cm.created_on
WHERE cm_newer.created_on IS NULL
GROUP BY c.id 
ORDER BY cm.created_on DESC

http://sqlfiddle.com/#!2/5dfea/18