如何每天显示两个表中的所有时间记录

时间:2018-11-25 16:00:12

标签: mysql

我在下面给出了mysql查询,以输出单日所需的记录。运行良好。但我想显示两桌每天的所有时间记录。我的两个表都有unix时间戳

查询单日记录为

    // DAY DATA STATS
$stmt_check = $conn->prepare("SELECT * FROM webstats WHERE pubhash =? AND time BETWEEN $day6 AND $day5");
$stmt_check->bind_param("s", $pubhash);
$stmt_check->execute();
$stmt_check->store_result();
$numberofrowsimpresssday = $stmt_check->num_rows;

$stmt_check->close();

$sql2 = "SELECT SUM(click) AS click_sum FROM webstatsclick WHERE pubhash='$pubhash' AND time BETWEEN $day6 AND $day5";
         $result2 = mysqli_query($conn, $sql2);

         if (mysqli_num_rows($result2) > 0) {
            while($row = mysqli_fetch_assoc($result2)) {

$clickz = $row['click_sum'];
$clicks = $clickz ?: '0';

            }
         } else {

         }

?>
<br>
<?php echo $day6; ?>||<?php echo $numberofrowsimpresssday; ?>||<?php echo $clicks; ?>
<?php
// DAY STATS ENDS

这应该输出AS 1542758400 || 113 || 2其中  午夜时光||印象||点击

请帮助我。预先感谢。

新的更新代码

$sql2 = "SELECT 
    count(*) as 'impressions',
    unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
    sum(click) as 'clicks'
FROM `webadstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubadhash = B.pubadhash
WHERE A.pubadhash='$pubadhash'
GROUP BY date(from_unixtime(A.time))";

$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
    while($row = mysqli_fetch_assoc($result2)) {
        $impressions[] = $row['impressions'];
        $clicksall[] = $row['clicks'];
        $timestamp[] = $row['timestamp'];
    }


   for($i=0; $i<count($clicksall); $i++){
    $str .= $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i] . ',';
    }
}
echo $str;

1 个答案:

答案 0 :(得分:0)

我认为您的要求可以通过GROUP BY和DATE()函数解决。看到以下问题:MySQL/SQL: Group by date only on a Datetime column

您还需要使用from_unixtime()才能将时间戳转换为日期。看到这个问题: Convert Unix timestamp into human readable date using MySQL

SELECT count(*),
       unix_timestamp(date(from_unixtime(time))) as 'timestamp' 
FROM webstats 
WHERE pubhash =? 
GROUP BY date(from_unixtime(time))

SELECT SUM(click) AS 'click_sum',
       unix_timestamp(date(from_unixtime(time))) as 'timestamp' 
FROM webstatsclick 
WHERE pubhash='$pubhash' 
GROUP BY date(from_unixtime(time))

编辑:为帮助您解决特定情况,可以清理您的PHP代码,并且您可以在一个查询中执行所有操作,而不是两个查询。见下文:

$sql2 = "SELECT 
    count(*) as 'impressions',
    unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
    sum(B.click) as 'clicks'
FROM `webstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubhash = B.pubhash
WHERE A.pubhash='$pubhash'
GROUP BY date(from_unixtime(A.time))";

$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
    while($row = mysqli_fetch_assoc($result2)) {
        $impressions[] = $row['impressions']
        $clicksall[] = $row['clicks'];
        $timestamp[] = $row['timestamp'];
    }
    while($i=0; $i<strlen($clicksall); $i++){
        $str .= '<br>' . $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i];
    }
}
echo $str;