MySQL GROUP仅当两列匹配

时间:2015-11-28 18:35:00

标签: mysql sql

我只是在两个字段重复时才尝试对记录进行分组。 我正在设计一个社交分享照片应用程序。用户可以分享,喜欢和评论他们的照片。每个动作(分享,评论等)都会出现在他们的朋友墙上。

问题在于,当用户执行所有这三个操作时,图片会显示三次,而不是一次显示三个操作。

数据库中的数据是这样的(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

如果有人能提供帮助,我将很高兴,谢谢

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您正在寻找" SELECT DISTINCT"

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