在codeigniter中按COUNT分组会导致数据库错误

时间:2018-04-06 16:03:51

标签: php mysql codeigniter

我有以下代码:

public function date_range_customers($params){

       $start_app_date = $params['start_app_date'];
       $end_app_date   = $params['end_app_date'];           


       $this->load->database();
       $this->db->select(
        'COUNT(tbl_appointment.id) AS total',            
        'tbl_customer.cus_name',
        'tbl_customer.cus_email',
        'tbl_customer.cus_mobile'
      );   
      $this->db->join('tbl_customer', 'tbl_customer.id = tbl_appointment.customer_id','inner');
      $this->db->join('tbl_transaction','tbl_transaction.app_id = tbl_appointment.id','inner');
      $this->db->where("app_date BETWEEN '$start_app_date' AND '$end_app_date' AND trans_type_id=1");
      $this->db->group_by('total','desc');
      $query = $this->db->get('tbl_appointment');

当我尝试按“总计”分组时发生错误如下,

  

发生数据库错误错误号码:1056无法分组'总计'

     

SELECT COUNT(tbl_appointment.id)AS FROM tbl_appointment INNER总计   加入tbl_customer tbl_customerid =   tbl_appointmentcustomer_id内部加入tbl_transaction开启   tbl_transactionapp_id = tbl_appointmentid WHERE app_date   BETWEEN' 2018-01-01' AND' 2018-04-30' AND trans_type_id = 1 GROUP BY   total

     

文件名:C:/wamp64/www/theme/system/database/DB_driver.php

     

行号:691

1 个答案:

答案 0 :(得分:3)

您不应按聚合列分组

但你可能需要一个order_by for desc

   $this->load->database();
   $this->db->select(
    'COUNT(tbl_appointment.id) AS total',            
    'tbl_customer.cus_name',
    'tbl_customer.cus_email',
    'tbl_customer.cus_mobile'
  );   
  $this->db->join('tbl_customer', 'tbl_customer.id = tbl_appointment.customer_id','inner');
  $this->db->join('tbl_transaction','tbl_transaction.app_id = tbl_appointment.id','inner');
  $this->db->where("app_date BETWEEN '$start_app_date' AND '$end_app_date' AND trans_type_id=1");
  $this->db->group_by(array('cus_name','cus_email','cus_mobile'));     
  $this->db->order_by('total','desc');
  $query = $this->db->get('tbl_appointment');

为此,您应该按照选择

中的非聚合列添加组