即使没有结果,也可以从Mysql数据库中获得按月计数

时间:2016-09-02 05:51:00

标签: mysql codeigniter

我正在创建来自Mysql数据库的显示月份计数的图表。

执行以下查询:

$cash_query =  $this->db->query("select COUNT(*) as count_monthwise, MONTH(FROM_UNIXTIME(dt_added)) as month from `order` where user_id='1'  and status != '9' and payment_type = '1' GROUP BY month");
$cash_result = $cash_query->result();

输出:

Array
(
    [0] => stdClass Object
        (
            [count_monthwise] => 1
            [month] => 8
        )

    [1] => stdClass Object
        (
            [count_monthwise] => 2
            [month] => 9
        )

)

在上面的输出中,显示“count_monthwise”表示计数,而月份“8”表示“8月 - 8月”。

但我想显示所有月份的输出,如果在任何月份查找计数为0,则显示[count_monthwise] => 0

我想显示精确输出,如:

    Array
    (
        [0] => stdClass Object
            (
                [count_monthwise] => 1
                [month] => 1
            )
        [1] => stdClass Object
            (
                [count_monthwise] => 1
                [month] => 2
            )
            .
            .
            .
            .
            .
            .
            . 
        [10] => stdClass Object
            (
                [count_monthwise] => 0
                [month] => 11
            )
        [11] => stdClass Object
            (
                [count_monthwise] => 0
                [month] => 12
            )

    )

我已经使用了类似这样的foreach循环,但这不起作用。

循环

foreach($cash_result as $cash => $cash_value){
   for($i=0;$i<=11;$i++){
      if($i == $cash){
      }
   }
}

2 个答案:

答案 0 :(得分:0)

这可能是单向的:

SELECT 
 COALESCE(yourQuery.count_monthwise,0) AS monthwise_count,
 allMonths.month
(SELECT 1 AS month UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 ) AS allMonths
LEFT JOIN
(
 SELECT 
  COUNT(*) as count_monthwise, 
  MONTH(FROM_UNIXTIME(dt_added)) as month 
 from `order` 
 where user_id='1'  and status != '9' and payment_type = '1' 
 GROUP BY month
) AS yourQuery 
ON allMonths.month = yourQuery.month

答案 1 :(得分:0)

从数据库获取结果后使用以下方式不做复杂查询只是做一些代码扭曲

$cash_result = $cash_query->result_array(); // make it to array         
$month = range(1,12);  // month array
$new_array = array();
$counta = count($month);
for($i=0; $i<$counta ; $i++){
    foreach($arr as $key=>$row){
       if(($month[$i] == $row['month'])){
          $new_array[$i] = $arr[$key]; 
          break;
       }else{
          $new_array[$i] = array('count_monthwise' => 0,'month' => $month[$i]);       
       }
    }
}   
echo '<pre>'; print_r($new_array);