代码之家  ›  专栏  ›  技术社区  ›  shin

MYSQL,GROUP BY子句;这与sql\u mode=only\u full\u group\u by[duplicate]不兼容

  •  -1
  • shin  · 技术社区  · 8 年前

    下面的CodeIgniter查询给出了一个错误提示;

    SELECT列表的表达式#22不在GROUP BY子句中,包含 非聚集列“hw3.1”。hw_作业。id’,它在功能上不起作用 取决于GROUP BY子句中的列;这与 sql\u mode=only\u full\u group\u by

    SELECT *, `studentid`, COUNT(studentid),
    `be_user_profiles`.`first_name`, `be_user_profiles`.`last_name`
    FROM `be_user_profiles` 
    JOIN `be_users` ON `be_users`.`id`=`be_user_profiles`.`user_id` 
    JOIN `hw_homework` ON `be_user_profiles`.`user_id`=`hw_homework`.`studentid` 
    WHERE `be_user_profiles`.`advisor` = '20' 
    AND `hw_homework`.`date` < '2018-06-15 00:00:00' 
    AND `hw_homework`.`date` > '2017-08-24 00:00:00'
    AND `active` = 1 
    GROUP BY `be_user_profiles`.`user_id` 
    ORDER BY COUNT(studentid) DESC
    

    文件名:modules/organization/models/Mhomework。php

    行号:226

    $this->db->select('*,studentid,COUNT(studentid),be_user_profiles.first_name,be_user_profiles.last_name');
    $this->db->from('be_user_profiles');
    $this->db->join('be_users','be_users.id=be_user_profiles.user_id');
    $this->db->join('hw_homework','be_user_profiles.user_id=hw_homework.studentid');
    $this->db->where('be_user_profiles.advisor',$id);
    $this->db->where('hw_homework.date <',$to);
    $this->db->where('hw_homework.date >',$from);
    $this->db->where('active',1);
    $this->db->group_by('be_user_profiles.user_id');
    $this->db->order_by('COUNT(studentid)','DESC');
    $query = $this->db->get();
    

    我删除了 studentid 或者由studentid等添加group_,但都不起作用。

    mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    
    mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    

    我想修复代码,而不是周围的方式。

    1 回复  |  直到 8 年前
        1
  •  2
  •   O. Jones    8 年前

    在标准SQL中,很难使用 SELECT * 在查询中使用 GROUP BY . 为什么?标准SQL要求SELECTEed列也出现在GROUP BY子句中,具有功能上依赖于GROUP BY中提到的值的列除外。

    要编写聚合查询,最简单的方法是枚举SELECT中需要的列,然后再枚举GROUP BY中需要的列。MySQL的 notorious nonstandard extension to GROUP BY 允许您询问中未提及的列 分组依据 子句,并继续为这些列返回一些不可预测的值。

    * . 改变

     $this->db->select('*,studentid,COUNT(studentid),be_user_profiles.first_name,be_user_profiles.last_name');
    

    $this->db->select('studentid,COUNT(studentid),be_user_profiles.first_name,be_user_profiles.last_name');
    

    $this->db->group_by('be_user_profiles.user_id');
    

    $this->db->group_by('studentid,be_user_profiles.user_id');