0

我最终得到了 PHP 中最糟糕的编写代码(它可以工作,但太可怕了!,也许你可以告诉我一个更好的方法)。我正在尝试在我的网页上显示 14 天的统计数据。我需要每天显示 4 个值(下载、上传的文件数;下载和上传的文件大小)。我有 2 个表(文件和 downloads_log),结构是:

文件 (file_name, file_size, upload_datetime) downloads_log (file_name, dl_datetime)

所以我需要以下内容:

Count all files uploaded from table `files` in specific day
Count all files downloaded from table `downloads_log` in specific day
SUM file_size in table `files` in specific day
SUM file_size in table `files` where files.file_name = downloads_log.file_name in specific day

这就是我过去 14 天所需要的。

还有我已经完成的“脚本”:

  for($i = 13; $i >= 0; $i--) {
    $query_downloads  = mysqli_query($con, "SELECT files.file_name, files.file_size, downloads_log.dl_file_name, downloads_log.dl_datetime, COUNT(file_name), SUM(file_size) FROM files, downloads_log WHERE files.file_name = downloads_log.dl_file_name AND `dl_datetime` >= '".date("Y-m-d", strtotime("-$i day"))." 00:00:00' AND `dl_datetime` <= '".date("Y-m-d", strtotime("-$i day"))." 23:59:59'");
    $result_downloads = mysqli_fetch_assoc($query_downloads);

    $query_uploads  = mysqli_query($con, "SELECT file_name, file_size, COUNT(file_name), SUM(file_size) FROM files WHERE `upload_datetime` >= '".date("Y-m-d", strtotime("-$i day"))." 00:00:00' AND `upload_datetime` <= '".date("Y-m-d", strtotime("-$i day"))." 23:59:59'");
    $result_uploads = mysqli_fetch_assoc($query_uploads);
  }

请建议我,如何用更简单的方法解决这个问题,不要给 mysql 带来巨大的负载,谢谢:)

4

2 回答 2

2
$i = 13;

$query = mysqli_query($con, "SELECT files.file_name, files.file_size, downloads_log.dl_file_name, downloads_log.dl_datetime, DATE(dl_datetime) AS datum, COUNT(file_name), SUM(file_size) FROM files, downloads_log WHERE files.file_name = downloads_log.dl_file_name AND `dl_datetime` >= '".date("Y-m-d", strtotime("-$i day"))." 00:00:00' AND `dl_datetime` <= '".date("Y-m-d", strtotime("-$i day"))." 23:59:59' GROUP BY DATE_FORMAT(dl_datetime, '%Y%m%d')");
while ($result = mysqli_fetch_assoc($query))
    $result_downloads[$result['datum']] = $result;

$query = mysqli_query($con, "SELECT file_name, file_size, COUNT(file_name), SUM(file_size), DATE(upload_datetime) AS datum FROM files WHERE `upload_datetime` >= '".date("Y-m-d", strtotime("-$i day"))." 00:00:00' AND `upload_datetime` <= '".date("Y-m-d", strtotime("-$i day"))." 23:59:59' GROUP BY DATE_FORMAT(upload_datetime, '%Y%m%d')");
while ($result = mysqli_fetch_assoc($query))
    $result_uploads[$result['datum']] = $result;

这将查询按不同的日期分组:GROUP BY DATE_FORMAT(upload/dl_datetime, '%Y%m%d')通过创建唯一的日时间戳(%Y = 4 位数年份,%m = 2 位数月份,%d = 2 位数日期)

结果以日期为索引填充到数组 $result_uploads/downloads 中。

于 2013-04-10T15:08:59.747 回答
2

希望这可以帮助:

SELECT files.file_name, files.file_size, downloads_log.dl_file_name, downloads_log.dl_datetime, COUNT(file_name), SUM(file_size) 
FROM files
join downloads_log on files.file_name = downloads_log.dl_file_name and to_days(now())-14<to_days(dl_datetime)
group by to_days(dl_datetime) 

在另一个查询上使用相同的想法。你会好起来的。

它每天选择过去 14 天和组。

于 2013-04-10T15:10:01.850 回答