2

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

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 条目呢?

谢谢!

4

2 回答 2

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
于 2012-08-10T17:12:46.757 回答
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

于 2012-08-10T17:33:59.330 回答