按组排序的数据

Sorted data in groups

数据集:

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

我想按 activitypostid 分组,同时按 id 降序排列结果。并希望每个组都有最新的 iduid。我不明白为什么这个查询没有 return 预期的输出。

据我了解 id 价值正在增加。要获取最新值,您可以使用聚合函数 MAX().

此外,您的带排序的内部查询是不必要的,因为在为 GROUP_CONCAT().

构建结果时,引擎必须按 id 对结果集进行排序

要检索特定 id 列的 uid,您需要自行连接到相同的 table。

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

可能最简单的方法是 group_concat()/substring_index() 技巧:

SELECT MAX(ID) as id,
       SUBSTRING_INDEX(GROUP_CONCAT(uid ORDER BY ID DESC), ',', 1) as uid,
       GROUP_CONCAT(DISTINCT uid ORDER BY id DESC) as uid_list,
       COUNT(*) as groupCount,
       activity, postid
FROM user_activities ua
GROUP BY activity, postid
ORDER BY id DESC;

这种方法有一些限制,因为 GROUP_CONCAT() 具有中间值的最大长度。通常默认值就足够了,但如果有很多行与每个组匹配,则您可能需要更改该值(并且您已经为 uid 的列表遇到了这个问题)。