PHP - Mysql查询:按天显示订单数量并存储在变量中

时间:2012-06-09 19:15:01

标签: php mysql

我有一个具有这种结构的表:

table name: customer_history

id| orders | order_date (timestamp) |  status    |  
--------------------------------------------------
 1|   1    | 2012-05-29 13:11:59    |  active    |
 2|   1    | 2012-05-29 13:11:59    |  active    |
 3|   1    | 2012-05-30 13:11:59    |  canceled  |
 4|   1    | 2012-05-31 13:11:59    |  trialing  |

我需要查询数据库并计算总订单数,其中状态!=已取消,每天返回一个日历月,并为每日总计分配一个唯一变量。

昨天的订单总额将是$ day-1,两天前$ day-2等等。

编辑以下答案。

$query = "SELECT 
            COUNT(*) AS number, 
            DATE(order_date) AS order_day 
        FROM 
            customer_history
        WHERE 
            status <> 'canceled' 
        GROUP BY 
            order_day 
        ORDER BY 
            order_date 
        DESC
        LIMIT 31";

$result = mysql_query($query) or die(mysql_error());

$i = 1;
$days = array();

while($row = mysql_fetch_assoc($result)) {

      $days[$i] = $row;
      $i++;
}

echo $days[1]['number'];
echo $days[2]['number'];
echo $days[3]['number'];
echo $days[4]['number'];
echo $days[5]['number'];
echo $days[6]['number'];

2 个答案:

答案 0 :(得分:1)

SELECT COUNT(*) AS number, DATE(order_date) AS order_day FROM orders WHERE status <> 'canceled' GROUP BY order_day ORDER BY order_date DESC LIMIT 31

然后循环结果。第一个是当天,第二个是昨天,第三个是前天等。

修改

包括循环/变量:

    <?php

$query = "SELECT 
                COUNT(*) AS number, 
                DATE(order_date) AS order_day 
            FROM 
                orders 
            WHERE 
                status <> 'canceled' 
            GROUP BY 
                order_day 
            ORDER BY 
                order_date 
            DESC
            LIMIT 31";

    $result = mysql_query($query);

    $i = 1;
    $days = array();

    while($row = mysql_fetch_assoc($query)
    {
        $days[$i] = $row;
        $i++;

    }

    ?>

echo $ days [1] ['number']为您提供今天的订单数量,昨天的$ days [2] ['number']等等。您可以通过回显$ days [x]输出实际日期] [ 'order_day']。

答案 1 :(得分:1)

使用GROUP BY order_date

尝试此查询
SELECT COUNT(*) AS number, DATE(order_date) AS order_day
FROM orders WHERE status != 'canceled' 
GROUP BY order_date ORDER BY order_date DESC