2014-03-28 17 views
1

我使用下面的查詢得到同樣的對話的最新消息2:使用組之前,限制通過

SELECT * 
FROM messages 
WHERE conversation_id 
IN (122806, 122807) 
GROUP BY conversation_id 
ORDER BY sent_on DESC 
LIMIT 2 

enter image description here

它會返回message7message3作爲結果。 我需要的是獲得由conversation_id分組最新的2個消息,因此結果應該是:

message3 
message1 
message4 
message5 
+0

來增加它。通過ORDER BY輕鬆使用GROUP BY的最佳方式是子查詢。 – aurbano

+0

@Chevis,謝謝你能告訴我如何 – Moussawi7

+1

可能重複[獲取每組分組結果的前n個記錄](http://stackoverflow.com/questions/12113699/get-top-n-records-for-每組的結果) – Rikesh

回答

1

的規範辦法做到這一點與where子句中的計數器:

select m.* 
from message m 
where 2 >= (select count(*) 
      from message m2 
      where m2.conversation_id = m.conversation_id and 
        m2.sent_on >= m.sent_on 
      ); 

message(conversation_id, sent_on)的指數肯定會幫助這個查詢。這也假設sent_on是獨特的。否則,您可以使用id

更有效的方法是使用變量:

select m.* 
from (select m.*, 
      @rn := if(@conversation_id = conversation_id, @rn + 1, 1) as rn, 
      @conversation_id := conversation_id 
     from message m cross join 
      (select @conversation_id := '', @rn := 0) const 
     order by conversation_id, sent_on desc 
    ) m 
where rn <= 2; 
+0

我嘗試了第一個方法,它使我的mysql服務器崩潰:'(讓我試試第二個方法(我有更多的200,000條記錄) – Moussawi7

+0

第二個方法返回:未知列'message_id' – Moussawi7

+0

另外第二種方法崩潰 – Moussawi7

0

嘗試GROUP BY和ORDER BY是這樣的:

SELECT GROUP_CONCAT(messages) 
FROM(
    SELECT * 
    FROM messages 
    ORDER BY sent_on DESC 
    )temp 
GROUP BY conversation_id 
LIMIT 2; 
+0

不工作,它只返回前兩條消息 – Moussawi7

+0

它會,如果你想所有的消息嘗試group_concatenating消息,編輯ans – avisheks

1

一條路可走這個使用GROUP_CONCAT()SUBSTRING_INDEX(),但它會告訴你,不是你在查詢中指定的分隔符分隔的消息與對話id作爲各行的foreach消息,您可以使用GROUP_CONCAT函數ORDER BY條款我也有ORDER BY sent_on DESC,這些郵件將被sent_on

SELECT conversation_id, 
SUBSTRING_INDEX(
GROUP_CONCAT(message ORDER BY sent_on DESC SEPARATOR '||'), 
'||',2) two_messages 
FROM messages 
/* 
optional where filter i have provided example for all conversations 
WHERE conversation_id 
IN (122806, 122807) */ 
GROUP BY conversation_id 
ORDER BY sent_on DESC 
進行分組和排序

另請注意,在GROUP_CONCAT()上設置了默認的1024個字符限制,但您也可以通過遵循GROUP_CONCAT()手冊

+1

謝謝,它工作正常,但正如你所提到的,它顯示了分隔符隔離的消息,所以你認爲沒有辦法按行來實現它?! – Moussawi7

+0

我想應該有一種方法去獲得每一行中的消息,但我不能有一個解決方案:) –