如何将普通的mysql查询转换为codeigniter

时间:2017-02-02 05:01:52

标签: mysql sql codeigniter

我想从标记表中获得最高分,但我已将获得的标记设置为varchar,因为我想在某些情况下存储一些文本值。

当我在mysql中写这个时,它返回最高标记为整数值

SELECT MAX(`mark_obtained`) AS `mark_obtained` FROM `mark` WHERE `exam_id` = '1' AND `class_id` = '10' AND `section_id` = '32' AND `subject_id` = '21' AND `mark_obtained` BETWEEN 0 AND 100

这是我编写的codeigniter方法获得最高分,但是当我给它打印它打印的值时,它总是打印varchar值

   function get_highest_marks($exam_id, $class_id, $section_id, $subject_id) {

        $this->db->where('class_id', $class_id);
        $this->db->where('section_id', $section_id);
        $this->db->where('subject_id', $subject_id);
        $this->db->where( "mark_obtained BETWEEN 0 AND 100", NULL, FALSE );

        $highest_marks = $this->db->get('mark')->result_array();



        foreach ($highest_marks as $row) {


            echo $row['mark_obtained'];
        }
    }

所以如何始终打印最高整数值

4 个答案:

答案 0 :(得分:0)

尝试以下查询。使用$this->db->select_max('column_name');。像这样

    $this->db->select_max('CAST(mark_obtained AS UNSIGNED)');
    $this->db->where('class_id', $class_id);
    $this->db->where('section_id', $section_id);
    $this->db->where('subject_id', $subject_id);
    $this->db->where( "mark_obtained >=", 0);
    $this->db->where( "mark_obtained <=", 100);

    $highest_marks = $this->db->get('mark')->row();

    echo $highest_marks->mark_obtained;

答案 1 :(得分:0)

您可以尝试以下代码

[PFObject]

答案 2 :(得分:0)

function get_highest_marks($exam_id, $class_id, $section_id, $subject_id) {
        $this->db->select('MAX(mark_obtained) AS mark_obtained');
        $this->db->where('exam_id', $exam_id);
        $this->db->where('class_id', $class_id);
        $this->db->where('section_id', $section_id);
        $this->db->where('subject_id', $subject_id);
        $this->db->where('mark_obtained >=', 0);
        $this->db->where('mark_obtained <=', 100);
        $highest_marks = $this->db->get('mark')->result_array();
        foreach($highest_marks as $key=>$val) {
            echo $val = (int)$highest_marks[$key]['mark_obtained'];
        }
}

function get_highest_marks($exam_id, $class_id, $section_id, $subject_id) {
    $query = $this->db->query("SELECT MAX(mark_obtained) AS mark_obtained FROM mark 
    WHERE exam_id = '".$exam_id."' AND class_id = '".$class_id."' AND section_id 
    = '".$section_id."' AND subject_id = '".$subject_id."' AND mark_obtained 
    BETWEEN 0 AND 100");
    if($query->num_rows() > 0){
          $result = $query->row_array();
          echo $result['mark_obtained'];
    }
}

答案 3 :(得分:0)

试试这个: -

$data = array('exam_id'=>1,'class_id'=>10,'section_id'=>32,'subject_id'=>32);
$this->db->select_max('mark_obtained') as 'mark_obtained';
$this->db->from('mark');
$this->db->where($data);
$this->db->where('mark_obtained >=', 0);
$this->db->where('mark_obtained <=', 100);
return $this->db->get('mark')->row()->mark_obtained;