简体   繁体   English

mysql选择过去7天的每一天记录

[英]mysql select each day record for the last 7 days

how do you select each day records for the last 7 days? 您如何选择最近7天的每日记录? if the dates are not available set it to 0. I tried the below but I am not getting any results. 如果日期不可用,请将其设置为0。我尝试了以下操作,但未得到任何结果。

$stmt = $db->prepare("SELECT DATE(order_date),COUNT(id) as 'total' FROM `orders` WHERE `order_date` BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()GROUP BY DATE(order_date)");
$stmt->execute();
$result = $stmt->get_result();

$total = [];
while($row = $result->fetch_object()){
    $total[] = $row->total;
}
print_r($total);

not the actual solution I wanted but I managed to get the results by wrapping the query in a function and calling it 7 times... 不是我想要的实际解决方案,但我设法通过将查询包装在函数中并调用7次来获得结果。

function weeklyData($day){
    $stmt = $db->prepare("SELECT order_date from orders where DATE(FROM_UNIXTIME(order_date)) = CURDATE() - INTERVAL ? DAY");
    $stmt->bind_param('s', $day);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows;
}
$total = [];
for($x = 1; $x <= 7; $x++){
    $total[] = weeklyData($x);
}
print_r($total);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM