从两个表中获取统计数据

时间:2017-08-15 11:13:08

标签: php mysql

两个表 - posts - 和users,公共列 - posts.user / users.id

我需要输出一些统计数据,即每个用户今天有多少帖子,持续7-30-365天和总计数。

下面的代码有效,但如果可能的话,我很有兴趣减少查询次数。

$stmt0 = $db->query("select * from users where role = 'mod' order by name asc");
    $count0 = $stmt0->rowCount();
    while($row0 = $stmt0->fetch()){
        $stmt1 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) = date(now())");
        $stmt2 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) > curdate() - interval 7 day");
        $stmt3 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) > curdate() - interval 30 day");  
        $stmt4 = $db->query("select id from posts where user = " . $row0['id'] . " and date(date) > curdate() - interval 365 day");
        $stmt5 = $db->query("select id from posts where user = " . $row0['id']);
   }

$count1 = $stmt1->rowCount();
$count2 = $stmt2->rowCount();
... etc.

1 个答案:

答案 0 :(得分:1)

MySQL查询:

SELECT  
    user,
    COUNT(DISTINCT CASE WHEN date = CURDATE() THEN id END)  as countToday,
    COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 7 DAY THEN id END)  as    count7,
    COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 14 DAY THEN id END) as    count14,
    COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 30 DAY THEN id END) as count30, 
    COUNT(DISTINCT CASE WHEN date >= CURDATE() - INTERVAL 365 DAY THEN id END) as count365,
    COUNT(*) as countAll
FROM posts
GROUP BY posts.user

使用PHP访问:

$res = $db->query($query); // set $query to my query
while($row = $res>fetch()){ // loop the result
    // access your row here
    echo $row["user"] // $row["countToday"] ...
}