2013-08-22 143 views
0

在我的MySQL數據庫中,我有用於從任何人如何按行分組但按最近日期分組?

id    int(11)   id of the message  
from member_id int(11)   id of the person the message was sent from 
to member_id  int(11)   id of the person the message was sent to 
date sent  datetime   date of when it was sent 
active   tinyint(1)  if the message is deleted  
text    longtext   the text of the message 
from_read  tinyint(1)  boolean to know if the person who sent it read it 
to_read   tinyint(1)  boolean to know if the person who it got sent to read it 

因此,例如,存儲的談話的消息像這樣的表,它可以像:

from_member_id to_member_id date sent 
1    2   june 12 
1    3   june 13 
2    3   june 14 
3    1   june 9 

所以我們的人之間的對話12,13,23

我試圖得到一個select語句,這將給我當前用戶是從每一個用戶在談話中涉及到的最新消息。因此,如果1在隨後登錄我希望拿到2行。結果集中的第一行將是上面的第二行(7月13日),因爲它是最近的,然後結果集中的第二行將是上面的第一行(6月12日),這是最近從1兩次談話。結果集也需要按發送日期排序,因此較新的對話列在最上面。

我想要做的就像是Android手機中的短信,您可以在其中看到對話列表以及每個列表中最近的消息。

這是我的SQL查詢

SELECT * 
FROM (
    SELECT * 
    FROM  message 
    WHERE `from member_id`=1 OR `to member_id`=1 
    ORDER BY IF(`from member_id`=1, `to member_id`, `from member_id`) 
) as t 
GROUP BY IF(`from member_id`=1, `to member_id`, `from member_id`) 

我只是硬編碼1現在是當前用戶。我正在做的是,按照我可以使用if語句檢查的其他人的ID對它們進行排序,然後對結果進行分組,以便嘗試從每個對話中獲取最近的一個。

問題是,在分組時,每個組可能有多於一行,而它似乎只是選擇一些隨機行。我如何才能選擇具有最新日期發送值的行?

回答

2

你在找這樣的事嗎?

SELECT m.* 
    FROM message m JOIN 
(
    SELECT from_member_id, to_member_id, MAX(date_sent) date_sent 
    FROM message 
    WHERE from_member_id = 1 
    GROUP BY from_member_id, to_member_id 
) q 
    ON m.from_member_id = q.from_member_id 
    AND m.to_member_id = q.to_member_id 
    AND m.date_sent = q.date_sent 
ORDER BY date_sent DESC 

輸出示例:

 
| FROM_MEMBER_ID | TO_MEMBER_ID | DATE_SENT | 
---------------------------------------------- 
|    1 |   3 | 2013-06-13 | 
|    1 |   2 | 2013-06-12 | 

這裏是SQLFiddle演示

UPDATE

SELECT m.* 
    FROM message m JOIN 
(
    SELECT LEAST(from_member_id, to_member_id) least_id, 
     GREATEST(from_member_id, to_member_id) greatest_id, 
     MAX(date_sent) date_sent 
    FROM message 
    WHERE from_member_id = 1 
     OR to_member_id = 1 
    GROUP BY LEAST(from_member_id, to_member_id), 
      GREATEST(from_member_id, to_member_id) 
) q 
    ON LEAST(m.from_member_id, m.to_member_id) = q.least_id 
    AND GREATEST(m.from_member_id, m.to_member_id) = q.greatest_id 
    AND m.date_sent = q.date_sent 
ORDER BY date_sent DESC 

輸出示例:

 
| FROM_MEMBER_ID | TO_MEMBER_ID | DATE_SENT | 
---------------------------------------------- 
|    3 |   1 | 2013-06-14 | 
|    1 |   2 | 2013-06-12 | 

這裏是SQLFiddle演示

+0

這工作時,最新的消息是從當前用戶。但它不考慮從其他用戶發送給當前用戶的消息。 – omega

+0

@omega查看可能的解決方案的更新答案 – peterm

+0

@omega它有幫助嗎? – peterm

0
SELECT 
    * 
FROM message m INNER JOIN 
    (
    SELECT 
     from_menber_id, 
     MAX(date_sent) AS sentdate 
    FROM message s 
    GROUP BY from_menber_id 
) AS a 
    ON m.date_sent = a.sentdate AND a.from_menber_id = m.from_menber_id 
+0

什麼是樣本? – omega

+0

對不起,這是表的名稱。我編輯過它。請看看這是你需要的。 – Nisha