数据集:
id uid activity postid
1 20 A 1
2 20 A 1
3 6 A 1
4 3 A 1
5 6 A 1
6 13 A 1
7 13 B 1
8 18 B 1
9 18 B 1
10 1 A 1
目前的结果:
id uid uid_list groupCount activity postid
9 18 18,13 3 B 1
1 20 1,13,6,3,20 7 A 1
预期成绩:
id uid uid_list groupCount activity postid
9 18 18,13 3 B 1
10 1 1,13,6,3,20 7 A 1
我的查询:
SELECT
id,
uid,
GROUP_CONCAT(DISTINCT uid ORDER BY id DESC) as uid_list,
COUNT(*) as groupCount,
activity,
postid
FROM (
SELECT *
FROM `user_activities`
ORDER BY id DESC) as tbl
GROUP BY
activity, postid
ORDER BY
id DESC
我希望按活动和postid分组,同时按id降序排列结果.并希望为每个群体拥有最新的id和uid.我不明白为什么这个查询不返回预期的输出.
最佳答案 据我所知,id值正在增加.要获取最新值,可以使用聚合函数MAX().
此外,您的内部查询与排序是不必要的,因为引擎必须在构建GROUP_CONCAT()的结果时按id对结果集进行排序.
要检索特定id列的uid,您需要自联接到同一个表.
SELECT
a.id, b.uid, a.uid_list, a.groupcount, a.activity, a.postid
FROM (
SELECT
MAX(id) as id,
GROUP_CONCAT(DISTINCT uid ORDER BY id DESC) as uid_list,
COUNT(*) as groupCount,
activity,
postid
FROM user_activities a
GROUP BY
activity, postid
) a
INNER JOIN user_activities b ON a.id = b.id