[英]Mysql + php : select count group by day and user
i have the tables below 我有下表
USER COMMENT
--------------------- -----------------------
| id | name | id | user_id | date
--------------------- -----------------------
| 1 | joe | 1 | 1 | 2014-10-10
| 2 | jane | 1 | 1 | 2014-10-10
| 3 | ted | 1 | 3 | 2014-10-11
My aim is to create a stats comparaison chart. 我的目的是创建一个统计比较表。 So i want to extract for each current week days, the number of comment added by each user.
因此,我想提取每个当前工作日中每个用户添加的评论数。 The expected array
预期的数组
-----------------------------
2014-10-10
-----------------------------
joe | 2
jane | 0
ted | 0
------------------------------
2014-10-11
------------------------------
joe | 0
jane | 0
ted | 1
I did a simple left join query and double group by, but the result was not formatted like expected. 我做了一个简单的左联接查询和双分组依据,但是结果的格式不符合预期。
Maybe, i have to sort and merge results using php?! 也许,我必须使用php来排序和合并结果?
Thank you for the help 感谢您的帮助
Here's my attempt: 这是我的尝试:
SELECT c1.date, c1.name, COUNT(c2.date)
FROM (
SELECT DISTINCT c.date, u.name, u.id
FROM COMMENT c
CROSS JOIN USER u) c1
LEFT JOIN COMMENT c2
ON c1.id = c2.user_id AND c1.date = c2.date
GROUP BY c1.date, c1.id
The difficulty was to obtain a list of all users for each date, which I produced with the sub query c1
. 困难在于获取每个日期的所有用户的列表,这是我用子查询
c1
。
What I would do is 我会做的是
Select User.name , Comment.date
From Comment Left Join User On Comment.user_id = User.id
Order By Comment.date Desc
This would return a list with user who commented + date. 这将返回带有评论+日期的用户的列表。
Now I would parse the result set :- 现在我将解析结果集:
$query = "query above";
$rowset = $db->fetchAll($query);
$result = array();
foreach ($rowset as $row) {
$result[$row['date']][$row[User]] += 1
}
This would give you an array 这会给你一个数组
Date1
=>user1
=>count
=>user2
=>count
Date2
=>user3
=>count
=>user4
=>count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.