2015-11-28 95 views
0

我試圖只在兩個字段重複自己時纔將一條記錄分組。 我正在設計一個社交分享照片應用程序。用戶可以分享,喜歡和評論他們的照片。每個動作(分享,評論等)都會出現在他們的朋友牆上。MySQL GROUP By僅當兩列匹配時

問題是,當用戶做所有三個動作時,圖片出現三次而不是三次動作。

數據在數據庫中是這樣(activities_tb)

id | photoID | uiID | action | date 
------------------------------------------- 
1 | 1  | 2 | like | 01/01/2015 
2 | 1  | 2 | share | 02/01/2015 
3 | 1  | 4 | share | 03/01/2015 
4 | 1  | 2 | comment | 04/01/2015 
5 | 2  | 4 | like | 04/01/2015 
6 | 2  | 2 | like | 05/01/2015 
7 | 2  | 3 | share | 05/01/2015 
8 | 2  | 4 | comment | 06/01/2015 
8 | 3  | 3 | like | 07/01/2015 
9 | 3  | 5 | like | 08/01/2015 
10 | 3  | 5 | comment | 08/01/2015 

查詢結果我想

id | photoID | uiID | action | date 
------------------------------------------- 
3 | 1  | 4 | share | 03/01/2015 
4 | 1  | 2 | comment | 04/01/2015 
6 | 2  | 2 | like | 05/01/2015 
7 | 2  | 3 | share | 05/01/2015 
8 | 2  | 4 | comment | 06/01/2015 
8 | 3  | 3 | like | 07/01/2015 
10 | 3  | 5 | comment | 08/01/2015 

這是我的發言

SELECT id, photoID, uiID, action, date 
FROM activities_tb 
GROUP BY photoID, uiID. 

這結合了所有的照片通過他們的ID返回只有三個結果

我會很高興,如果有人能有所幫助,謝謝

+0

http://sqlfiddle.com/#!9/02bfa9/1我得到3個以上的結果u_u – Blag

回答

0

您可以先選擇所需的ID和加入你的桌子上:

select tb.* 
from activities_tb tb 
join(select max(id) as id 
    from activities_tb 
    group by photoID, uiID) t on t.id = tb.id 
0

您正在尋找「SELECT DISTINCT」

SELECT DISTINCT photoID, uiID, action, date 
FROM activities_tb 
GROUP BY photoID, uiID.