【问题标题】:mysql group_concat with a count inside?mysql group_concat 里面有计数吗?
【发布时间】:2012-04-13 15:07:29
【问题描述】:

我有 2 个表,用户和关注者。下面的表有一个名为 status 的列。我想计算每个用户按状态分组的关注次数。

下面的查询为每个用户返回每个状态类型的记录。

SELECT users.name as user_name, f.status, count(f.id) 
FROM users
JOIN application_follows f ON f.user_id = users.id
GROUP BY users.id, f.status
ORDER BY users.id

返回类似:

user_name     status     count

mike          new         10
mike          old         5
tom           new         8
tom           old         9

但我想要更友好的东西,例如:

user_name     status_count

mike          new,10|old,5
tom           new,8|old,9

尝试使用 group_concat 和 count 但没有奏效。有什么线索吗?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您需要使用 GROUP BY 两次,首先在 (user_id, status) 上从 follow 获取计数,然后在 user_id 从连接表到 concat:

    SELECT users.name, GROUP_CONCAT( CONCAT(f.status, ',', f.cnt) SEPARATOR '|' )
    FROM users 
    JOIN
    ( SELECT user_id, status, count(id) AS cnt
      FROM application_follows
      GROUP BY user_id, status ) f
    ON f.user_id = users.id
    GROUP BY users.id
    

    【讨论】:

      【解决方案2】:

      我不知道完整的表定义,所以我创建了查询,它只使用了用户名、状态和计数。

      SELECT user_name, GROUP_CONCAT(CONCAT(status, ',', count) SEPARATOR '|')  FROM users GROUP BY user_name ORDER BY user_name;
      

      【讨论】:

        猜你喜欢
        • 2013-03-10
        • 2014-05-25
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        • 2017-12-19
        • 2018-05-11
        • 2010-09-23
        • 2019-08-09
        相关资源
        最近更新 更多