SQL查询重复结果

时间:2015-01-14 14:23:29

标签: php mysql

我有一个表,用于存储下载ID,帖子ID,文件名和时间戳

我做的是循环通过表中的所有行然后我再次循环以获得在00:00:00和23:59:59之间匹配的日期

这很好,并返回所有结果和我的下载计数。 问题是它重复很多次,因为在同一天下载的是同一个下载。

我不能使用array_unique或多维array_unique函数,因为它们带有时间戳,并且始终显示为唯一。

function download_stats_page_c(){
global $wpdb;
$downloads = $wpdb->get_results("SELECT custom_resource_download_log.* FROM custom_resource_download_log"); ?>

<script src="<?php echo get_template_directory_uri(); ?>/library/datatables/media/jquery.dataTables.min.js"></script>
<table id="downloads" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Post</th>
            <th>File</th>
            <th># of Downloads</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
 <?php
foreach ($downloads as $download) {
    $pid = $download->post_id; $file_id = $download->file_id; $time = $download->timestamp;
    $time_str = substr($time, 0, strrpos($time, ' '));
    $date_from = $time_str." 00:00:00";
    $date_to = $time_str." 23:59:59";
    $Q = "SELECT * FROM `custom_resource_download_log` WHERE `timestamp` BETWEEN '$date_from' AND '$date_to' AND `post_id` = '$pid'";
    $results = $wpdb->get_results($Q);
    foreach($results as $result) {
   ?>
    <tr>
        <td>
            <?php echo get_the_title($result->post_id); ?>
        </td>
        <td>
            <?php echo $result->file_name; ?>
        </td>
        <td>
            <?php echo $wpdb->get_var("SELECT COUNT(*) FROM custom_resource_download_log WHERE post_id='$pid' AND file_id='$file_id' AND `timestamp` BETWEEN '$date_from' AND '$date_to'"); ?>
        </td>
        <td>
            <?php echo $time_str; ?>
        </td>
    </tr>
  <?php
    }
}
echo "</tbody></table>";

} 

1 个答案:

答案 0 :(得分:0)

只需尝试此查询:

SELECT download_id, post_id, file_name, DATE(timestamp) as the_date, COUNT(*) as number_of_downloads 
FROM custom_resource_download_log
GROUP BY download_id, post_id, file_name, the_date ORDER BY the_date