如何在CodeIgniter中同时使用Select_sum和Select_max

tzdcorbm  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(157)

我想得到每个学生所有科目的总成绩,然后得到最高的总分。
这是为了得到总分

public function GetsumScore($exam_group_class_batch_exam_student_id) 
    {
       $this->db->select_sum('get_tot_score');
       $this->db->where('exam_group_class_batch_exam_student_id', $exam_group_class_batch_exam_student_id);
       return $this->db->get('exam_group_exam_results')->row(); 
     }

但是我现在有点困惑,不知道如何以及在哪里插入select_max查询。
有什么需要帮忙的吗?

uttx8gqw

uttx8gqw1#

这里有两种方法。

方法1

我下面提到的bounce是为了告诉你,你可以任意多次使用select语句。它将成为一个单一的查询。如果你愿意,你可以取消注解bounce。

public function GetsumScore($exam_group_class_batch_exam_student_id)
{
    //$this->db->select("*"); // Its a bounce too
    $this->db->select_sum("get_tot_score");
    $this->db->select_max("get_tot_score", "get_tot_score_max");
    //$this->db->select_avg("amount", "avg_amount"); // Its a bounce
    
    $this->db->where('exam_group_class_batch_exam_student_id', $exam_group_class_batch_exam_student_id);
    return $this->db->get("exam_group_exam_results")->row();
}

方法2

public function GetsumScore($exam_group_class_batch_exam_student_id)
{
    $this->db->select("(SELECT SUM(get_tot_score) FROM exam_group_exam_results WHERE exam_group_class_batch_exam_student_id = {$exam_group_class_batch_exam_student_id}) as get_tot_score");
    $this->db->select("(SELECT MAX(get_tot_score) FROM exam_group_exam_results WHERE exam_group_class_batch_exam_student_id = {$exam_group_class_batch_exam_student_id}) as get_tot_score_max");
    return $this->db->get()->row();
}

共享第二种方法的原因是知识。当我们需要一次添加多个查询时,所以不需要编写不同的方法或函数,我们可以在简单的$this->db->select中完成。
您也可以呼叫不同的数据表,而不与目前的数据表链接。

相关问题