每日页面比率MySQL查询

时间:2013-10-09 21:45:32

标签: php mysql

我正在使用cookie来跟踪网站流量,然后将其写入数据库。

我正在尝试获取我的目标网页index.php的每日比率以及要在图表中显示的所有其他网页的平均值。

我正在努力研究MySQL查询的语法。

我想要查询中的2个值:$ row-> day和$ pageRatio并显示过去30天的这些值。

我的数据库由一个名为tracking的表组成,其中包含以下字段:id,cid,referrerDomain,referrer,page,ip,reverseIP,userAgent,lang,date

页面字段包含网页名称,例如:index.php,other.php等。

$sql = "SELECT (
                 SELECT COUNT(`page`) FROM `tracking`
                 WHERE `page` = 'index.php'
                 AND DISTINCT(`date`)
                 GROUP BY DATE(`date`) ) AS indexCount,

             (
             SELECT COUNT(`page`) FROM `tracking`
             WHERE `page` != 'index.php' 
             AND `date`
             BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY)
             AND NOW()
             GROUP BY DATE(`date`) ) AS otherPageCount,

                 DATE(`date`) AS day
                 FROM `tracking`
                 WHERE `date`
                 BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY)
                 AND NOW()
                 GROUP BY DATE(`date`)";

      $sqlprep = $conn->prepare($sql); 

      if($sqlprep->execute()) {
                $completedAmount = 0;
          while($row = $sqlprep->fetch(PDO::FETCH_OBJ)){

                $pageRatio = $row->indexCount / $row->otherPageCount;

                echo "['" . $row->day . "', " . $pageRatio . "],\n";

           }

         }

我找到的解决方案是一个公认的答案:How do I combine these 3 queries into one MySQL query?

SELECT DATE(`date`),
       COUNT(`page`) AS indexCount, 
       SUM(`page` = 'index.php') as idx_count, 
       SUM(`page` <> 'index.php') as not_idx_count
FROM `tracking`
WHERE `date` BETWEEN DATE_ADD(NOW(),INTERVAL -30 DAY) AND NOW()
GROUP BY DATE(`date`)

1 个答案:

答案 0 :(得分:1)

可能这也会起作用

SELECT DATE(`date`),
       COUNT(`page`) AS indexCount, 
       SUM(`page` = 'index.php') as idx_count, 
       SUM(`page` <> 'index.php') as not_idx_count
       TIMESTAMPDIFF(DAY,date,now()) as days
FROM `tracking` GROUP BY DATE(`date`) having days <30