我一直在思考,我自己无法解决这个问题。
我有这个mysql表,其中包含网站访问者的统计信息
+-----------------------------+
+ date | visits +
+-----------------------------+
+ 2014-03-02 | 736 +
+ 2014-03-03 | 936 +
+ 2014-03-06 | 54 +
+-----------------------------+
我想回复一周的统计报告,但也会显示该表没有数据的日期。
输出应为:
2014-03-01: 0
2014-03-02: 736
2014-03-03: 936
2014-03-04: 0
2014-03-05: 0
2014-03-06: 54
2014-03-07: 0
请注意我知道如何使用此功能执行此操作:
$first = '2014-03-01';
$last = '2014-03-07';
while (strtotime($first) <= strtotime($last)) {
$related10 = mysql_query("SELECT * FROM stats WHERE date >= '$first' and date <= '$last'");
$rows = mysql_fetch_array($related10);
$date = $rows['date'];
$visits = $rows['visits'];
echo ''.$date.': '.$visits.'';
$first = date("Y-m-d", strtotime("+1 day", strtotime($first)));
}
但是这个函数的问题是它为每个日期运行一个sql查询,对于大日期范围,它在加载页面时会持续几分钟。
我想用一个SQL查询来完成这个
它应该是这样的
$related10 = mysql_query("SELECT * FROM stats WHERE fecha >= '$first' and fecha <= '$last'");
while($rows = mysql_fetch_array($related10)) {
//function to add the missing date data.
echo $output;
}
有谁知道如何解决这个问题?
非常感谢你。
答案 0 :(得分:0)
你的表现是正确的!
您可以获取所有记录一次并将它们保存在数组中,其中日期将是关键。然后,在循环中,您可以检查数组中是否存在该日期。
答案 1 :(得分:0)
// first put the date value into the "key" of each array item
$rows2 = array();
foreach ($rows as $row) {
$rows2[$row['date']] = $row['visits'];
}
$currentTs = strtotime('2014-03-01');
$lastTs = strtotime('2014-03-07');
while ($currentTs < $lastTs) {
$displayDate = date('Y-m-d', $currentTs);
echo $displayDate . " = ";
if (!empty($rows2[$displayDate])) {
echo $rows2[$displayDate]; // echo the visits
}
else {
echo '0';
}
echo "\n";
$currentTs = strtotime('+1 day', $currentTs);
}
答案 2 :(得分:0)
如果您愿意创建一个小型实用程序表,则可以使用this solution (SQLFiddle)。
CREATE TABLE ints ( i tinyint );
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
然后在PHP中
$related10 = mysql_query("
SELECT calendar.date,
ifnull(stats.visits, 0) AS visits
FROM (SELECT DATE('$first') + INTERVAL a.i*100 + b.i*10 + c.i DAY AS date
FROM ints a
JOIN ints b
JOIN ints c
WHERE (a.i*100 + b.i*10 + c.i) <= DATEDIFF('$last', '$first')
) calendar
LEFT JOIN stats ON stats.date = calendar.date
ORDER BY calendar.date
");
如果您需要处理超过1000天的差异,只需继续向ints
表添加联接,并将乘法乘以10,直到您可以覆盖所需的日期。感谢Brian Showalter在http://www.brianshowalter.com/calendar_tables了解SELECT
日历数据的想法。