簡體   English   中英

mysql group_concat里面有一個count?

[英]mysql group_concat with a count inside?

我有2個表,用戶和以下。 table follow有一個名為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並計數但沒有工作。 有線索嗎?

您需要使用GROUP BY兩次,首先在(user_id,status)中從以下獲取計數然后在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

我不知道完整的表定義所以我創建了查詢,它只使用user_name,status和count。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM