2012-08-10 88 views
2

最新的文本輸入我有一個數據庫,在那裏我把郵件會話得到GROUP BY的語句

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,但對於相應的文本輸入?

謝謝!

+0

的可能重複[MySQL的:使用LIMIT GROUP BY內,讓每N組結果](http://stackoverflow.com/問題/ 2129693/mysql-using-limit-group-by-to-get-n-results-per-group) – 2012-08-10 17:35:44

回答

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 
+0

這對我來說非常適合!謝謝! – Kinesias 2012-08-10 18:26:51

+0

很好..考慮接受答案和upvote,如果它爲你工作.. :) – 2012-08-11 04:56:54

+0

@MatthiasLang ^^ – 2012-09-20 17:58:32

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