php - get statistic data from two tables -


two tables - posts - , users, common column - posts.user/users.id

i need output statistic data, i.e. how posts each user has today, last 7-30-365 days , total count.

the code below works, i'm interesting reduce number of queries, if possible.

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

the mysql query:

select       user,     count(distinct case when date = curdate() id end)  counttoday,     count(distinct case when date >= curdate() - interval 7 day id end)     count7,     count(distinct case when date >= curdate() - interval 14 day id end)    count14,     count(distinct case when date >= curdate() - interval 30 day id end) count30,      count(distinct case when date >= curdate() - interval 365 day id end) count365,     count(*) countall posts group posts.user 

access php:

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

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -