mysql 计数 group,mysql group_concat里面有一个计数?

i have 2 tables, users and follows. table follows has a column named status. I would like to count how many follows each user has grouping by the status.

The query below returns a record for each status type for each user.

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

returns something like:

user_name status count

mike new 10

mike old 5

tom new 8

tom old 9

but i would like something more friendly like:

user_name status_count

mike new,10|old,5

tom new,8|old,9

tried using group_concat and count but didnt work. Any clues?

解决方案

You need to use GROUP BY twice, first on (user_id, status) from follows to get counts then on user_id from joined table to 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值