2014-01-15 30 views
0

對於notifications表,我有以下表結構。在MySql中按類型分組通知

id user_id post_id type status date  seconduser_id 
1 1  23  1  0  somedate 4 
2 2  25  2  0  somedate 3 
3 3  26  1  0  somedate 4 
4 4  28  2  1  somedate 5 
5 5  21  2  0  somedate 4 
--- 
--- 
and so on 

這裏type = 1liketype = 2commentstatus = 0表示seconduser_id尚未看到通知。 seconduser_id是通知收件人。

是否有可能獲得1個用戶(例如seconduser_id = 4)通知,由type分組通知,顯示count和最新user_id每個type(在一個查詢)?

執行此操作將會像User3和其他10人喜歡你的帖子。

編輯:到目前爲止,我有東西拉動所有通知user 4,然後在php中進行分組。我不認爲這是有效的,所以在尋找更好的解決方案。

+1

請顯示您的嘗試。 –

+0

你可以添加預期的結果作爲例子嗎? –

+0

@GordonLinoff done編輯 – pewpewlasers

回答

1

最基本的答案是聚合查詢。併發症是獲取每種類型的最新用戶ID。有一個方法,使用substirng_index()/group_concat()

select type, count(*), 
     substring_index(group_concat(user_id order by id desc), ',', 1) as latest_user 
from notifications n 
where secondaryuser_id = 4 and status = 0 
group by type; 

我不知道,如果你也想通過status過濾。

編輯(由OP加):

雙方post_idtype使用上述代碼和分組。因爲你想說用戶1和10其他人喜歡你的帖子。對於每個分組通知,這意味着post_id必須是唯一的。

SELECT *, substring_index(group_concat(user_id order by id desc), ',', 1) as latest_user, COUNT(post_id) AS total 
FROM notifications n 
WHERE seconduser_id = 4 and status = 0 
GROUP BY post_id, type 
+0

感謝您的輸入,我稍微修改了您的答案,使其更實用。 – pewpewlasers

0

試試這個:

SELECT MAX(user_id) AS LatestUser, type, COUNT(type) AS total 
FROM notifications 
WHERE seconduser_id = 4 
GROUP BY type