php - 在 codeigniter 中按 COUNT 分组使数据库错误

标签 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');

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

A Database Error Occurred Error Number: 1056 Can't group on 'total'

SELECT COUNT(tbl_appointment.id) AS total FROM tbl_appointment INNER JOIN tbl_customer ON tbl_customer.id = tbl_appointment.customer_id INNER JOIN tbl_transaction ON tbl_transaction.app_id = tbl_appointment.id WHERE app_date BETWEEN '2018-01-01' AND '2018-04-30' AND trans_type_id = 1 GROUP BY total

Filename: C:/wamp64/www/theme/system/database/DB_driver.php

Line Number: 691

最佳答案

你不应该按聚合列分组

但是你可能需要一个 order_by 来获取总描述

   $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');

为此,您应该按选择中的非聚合列添加到组中

关于php - 在 codeigniter 中按 COUNT 分组使数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49696843/

相关文章:

php - 可以在不重新加载页面的情况下更改 sql 排序顺序吗?

PHP fputcsv 在 Excel 中以科学记数法显示长整数

php - 通过 getSingleScalarResult() 和 groupBy() 获取计数查询结果 - 异常

php - 在正常的 PHP session 中使用 CodeIgniter,在何处添加 session_start();

php - Laravel 4 中的事务和事件

php - PHP中如何使用$_GET获取多个同名参数

php - 从 mysql 表加载图像

具有动态列截断键值的 MySQL 数据透视表查询

javascript - 需要多次点击才能完成两个功能

javascript - 如何在 Codeigniter 中禁用 cookie 和缓存