MySQL查询 - 返回过去4个月的数据,如果某个月没有数据返回0

时间:2014-10-09 19:08:34

标签: mysql codeigniter

我的问题类似于这个问题:MySQL Query - return value for past 12 months record for each month

但我无法弄清楚如何使用我的查询来实现它。

我需要前4个月的数据,如果那个月没有输出0。

以下是我在codeigniter模型中的当前查询:

function getMonthlySumOrders()
{
    $this->db->select("SUM(price_each*quantity) AS sum_monthly_price, DATE_FORMAT(job.order_date, '%M') AS 'order_date', customer.company_name", false);
    $this->db->join('job', 'job.job_id = job_details.job_id');
    $this->db->join('customer', 'customer.company_id = job.company_id');
    $this->db->where('job.company_id', $this->uri->segment(3));
    $this->db->where('month(job.order_date)<=', date("m"));
    $this->db->where('month(job.order_date)>=', date("m")-3);
    $this->db->group_by('MONTH(job.order_date)');
    $this->db->order_by('job.order_date', "asc");
    $query = $this->db->get('job_details');

return $query->result_array();
}

function getMonthlySumCompleted()
{
    $this->db->select("SUM(price_each*quantity) AS sum_monthly_price", false);
    $this->db->join('job', 'job.job_id = job_details.job_id');
    $this->db->join('customer', 'customer.company_id = job.company_id');
    $this->db->where('job.company_id', $this->uri->segment(3));
    $this->db->where('month(job.completed_date)<=', date("m"));
    $this->db->where('month(job.completed_date)>=', date("m")-3);
    $this->db->group_by('MONTH(job.completed_date)');
    $this->db->order_by('job.completed_date', "asc");
    $query = $this->db->get('job_details');

return $query->result_array();
}

当查询返回正确日期的结果时,但没有值时不显示0,因此两组数据之间的顺序不同步。

1 个答案:

答案 0 :(得分:0)

试试这个:

if($query-num_rows() > 0)
{
return $query->result_array();
}
else
{
return "0";
}