1

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

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

我正在为 MySQL 查询的语法而苦苦挣扎。

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

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

page 字段包含网页名称,例如: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";

           }

         }

我在这里找到的解决方案是一个公认的答案:如何将这 3 个查询组合成一个 MySQL 查询?

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`)
4

1 回答 1

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
于 2013-10-10T11:39:09.127 回答