简体   繁体   中英

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?!

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM