按三列分组在CodeIgniter中不起作用

svujldwt  于 2022-12-07  发布在  其他
关注(0)|答案(4)|浏览(191)

我需要一个包含三列GroupBy的结果,而SQL运行得很好,没有任何问题。它不执行查询。我的代码和SQL如下。

代码

$this->db->select(['trk.userid AS user_id', 'scr.course AS course_id'])
                     ->from('mdl_scorm scr')
                     ->join('mdl_scorm_scoes_track trk', 'scr.id = trk.scormid', 'inner')
                     ->join('mdl_course_modules mcs', 'mcs.instance = scr.id', 'inner')
                     ->where_in('trk.value', ['completed','incomplete','passed'])
                     ->group_by(['scr.course', 'trk.userid', 'trk.scormid'])
                     ->order_by('trk.userid', 'DESC');

查询语句

SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id 
FROM (`mdl_scorm` scr) 
INNER JOIN `mdl_scorm_scoes_track` trk ON `scr`.`id` = `trk`.`scormid` INNER JOIN `mdl_course_modules` mcs ON `mcs`.`instance` = `scr`.`id` 
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed') 
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid` 
ORDER BY `trk`.`userid` DESC LIMIT 0,100;

当group_by只有两列时,

->group_by(['scr.course', 'trk.userid'])

原因何在?

xqk2d5yq

xqk2d5yq1#

*在codeigniter中,group_by() * 仅适用于 * 两个字段
一个月一个月

允许您编写查询的GROUP BY部分:

$this->db->group_by(array("title", "date"));  // Produces: GROUP BY title, date

CI 3 × group_by()

编辑01

$query=$this->db->query("
        SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id 
        FROM `mdl_scorm` scr 
        INNER JOIN `mdl_scorm_scoes_track` trk 
        ON `scr`.`id` = `trk`.`scormid` 
        INNER JOIN `mdl_course_modules` mcs 
        ON `mcs`.`instance` = `scr`.`id` 
        WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed') 
        GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid` 
        ORDER BY `trk`.`userid` 
        DESC LIMIT 0,100;");

$result = $query->result_array();
return $result;
sh7euo9m

sh7euo9m2#

考虑模型中的原始查询。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class xyz_model extends CI_Model{
     function __construct()
     {
          // Call the Model constructor
          parent::__construct();
     }

     function get_this_thing($month,$year) 
     {    $myQuery="SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id 
          FROM `mdl_scorm` scr 
          INNER JOIN `mdl_scorm_scoes_track` trk 
          ON `scr`.`id` = `trk`.`scormid` 
          INNER JOIN `mdl_course_modules` mcs 
          ON `mcs`.`instance` = `scr`.`id` 
          WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed') 
          GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid` 
          ORDER BY `trk`.`userid` 
          DESC LIMIT 0,100;";

          $query = $this->db->query($myQuery);

          $result = $query->result();
          return $result;
     }
}
x8diyxa7

x8diyxa73#

您也可以传递多个值的数组:

$this->db->group_by(array("title", "date"));  // Produces: GROUP BY title, date

Source link

kcrjzv8t

kcrjzv8t4#

使用结果数组而不是结果,如

return $query->result_array();

相关问题