2010-11-08 88 views
3

我有三個表組之前發生的順序,我會就在這裏顯示出相關的列的MySQL獲得由

表:組列:GROUP_ID,名稱。

表:groups_to_message色譜柱: GROUP_ID,MESSAGE_ID

表:消息色譜柱:MESSAGE_ID, 創建(日期)

我需要基本上找到每個組的最後一個消息,以進行顯示重複的組。

我使用GROUP BY試過這樣:

SELECT m.created, g.group_id 
FROM groupss as g 
JOIN group_to_message as gm ON (g.group_id = gm.group_id) 
JOIN messages as m 
GROUP BY g.group_id 
ORDER BY m.created DESC 

這將導致成功的分組,但ORDER BY所以第一個結果排序之前,在作出決定之前完成。

任何幫助表示讚賞。

+0

消息可以屬於多個組在你的模型中? – Quassnoi 2010-11-08 16:38:09

+1

你有沒有發現這方面的解決方案? – Ajinkya 2013-07-30 11:58:21

回答

0
SELECT m.created, g.group_id 
FROM groupss g 
JOIN messages m 
ON  m.id = 
     (
     SELECT mi.id 
     FROM group_to_message gm 
     JOIN message mi 
     ON  mi.message_id = gm.message_id 
     WHERE gm.group_id = g.group_id 
     ORDER BY 
       gm.group_id DESC, mi.created DESC 
     LIMIT 1 
     ) 
3

如果我正在閱讀您的問題,請使用MAX()。這應該讓你最近的項目爲每個組

例...

SELECT MAX(m.created), g.group_id 
FROM groupss as g 
JOIN group_to_message as gm ON (g.group_id = gm.group_id) 
JOIN messages as m ON (gm.message_id = gm.message_id) 
GROUP BY g.group_id 
ORDER BY m.created DESC 
+0

這給出了每個組的相同日期,即表中的最大日期 – wiggles 2010-11-08 16:49:51

0

這是未經測試,但它應該工作:

SELECT m.created, g.group_id 
FROM groups as g 
JOIN group_to_message as gm ON (g.group_id = gm.group_id) 
JOIN messages as m ON (gm.message_id = m.id) 
GROUP BY g.group_id HAVING m.created = MAX(m.created)