LEFT JOIN不输出所需的结果

时间:2013-09-03 03:17:52

标签: php mysql codeigniter

我在这里使用codeigniter进行示例查询。我正在使用它来获取满足我的条件的数据。

MODEL:

    function quarterly1_sales($year_date, $q1_start){
     $where = array(
     'status'   => 'purchased',
     'payment.paymentdate >=' => $q1_start,
     'payment.paymentdate <=' => 'DATE_ADD('.$q1_start.',INTERVAL 1 QUARTER)');
    return $this->db
    ->select('COUNT(payment.keyid) AS rec_count')
    ->select('product_key.client_name, product_key.contact_email, product_key.status, product_key.id, payment.paymentdate, (payment.id) as pid,payment.subscription_type')
    ->from('product_key')
    ->where($where)
    ->join('payment', 'payment.keyid=product_key.id', 'left outer')
    ->group_by('product_key.id')
    ->get()
    ->result(); 
    }

控制器:

if($data['filter'] == 'quarterly'){
//1st quarter of the year
    @$q1_start = date('Y-m-d', strtotime(date($year_date).'-01-01'));
$data['quarterly1_sales'] = $this->basemodel->quarterly1_sales($year_date, $q1_start);
$this->load->view('sales', $data);          
}

查看:

if($filter == 'quarterly'){
    $title = "Quarterly Sales Summary for ".$date_year;

    echo "<br /><strong>".$title."</strong></div>
        </tr>"<tr>
    <th>Name</th>
    <th>Email Address</th>
    <th>Payment Date</th>
    <th>Subtotal Amount</th>

“;

    foreach ($quarterly1_sales as $quarter1) :

        echo $client_name = $quarter1->client_name;
        echo $paymentdate = $quarter1->paymentdate;
        echo $email = $quarter1->contact_email;
        echo $recount= $quarter1->rec_count;
        echo $sum_amount = $recount * 588;
    if($recount == 0){
        $display = "display:none;";
    }else{
        $display = "";
    }

endforeach;

我的问题是,因为我的数据从2012年和2013年开始,所以不应该有任何结果,但它会输出所有内容。 希望有人可以帮助我。谢谢。

1 个答案:

答案 0 :(得分:1)

Codeigniter的活动记录类自动转义传递给where()函数的所有内容。因此,您对MySQL函数DATE_ADD()的调用将作为字符串传递,并由MySQL逐字处理而不是被评估。要解决此问题,请将where子句移动到单独的函数调用,并将第三个参数设置为FALSE,从而关闭转义。

$where = array(
     'status'   => 'purchased',
     'payment.paymentdate >=' => $q1_start);
    return $this->db
    ->select('COUNT(payment.keyid) AS rec_count')
    ->select('product_key.client_name, product_key.contact_email, product_key.status, product_key.id, payment.paymentdate, (payment.id) as pid,payment.subscription_type')
    ->from('product_key')
    ->where($where)
    ->where('payment.paymentdate <=', 'DATE_ADD('.$this->db->escape($q1_start).',INTERVAL 1 QUARTER)', FALSE)
    ->join('payment', 'payment.keyid=product_key.id', 'left outer')
    ->group_by('product_key.id')
    ->get()
    ->result();