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

时间:2015-01-09 01:12:48

标签: php mysql

如何选择过去7天的每日记录?如果日期不可用,请将其设置为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);

1 个答案:

答案 0 :(得分:1)

不是我想要的实际解决方案,但我设法通过将查询包装在函数中并调用它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);