Codeigniter得分排名

时间:2014-05-28 22:24:28

标签: php mysql codeigniter

我试图根据他们在桌子上的得分来获得学生的等级。它似乎并不太复杂,但我没有得到它。理想情况下,该函数将采用stu_id(整数)并根据包含“stu_id”,“stu_nm”和“stu_scr”列的表格输出其等级。

我在这里看过其他问题,但我不确定我是否理解如何将答案应用于我的具体问题。我看到这个解决方案是另一个线程尝试类似的东西:

SELECT s1.initials, (
  SELECT COUNT(*)
  FROM scores AS s2
  WHERE s2.score > s1.score
)+1 AS rank
FROM scores AS s1

并尝试将其应用于我修改为的代码:

$query = $this
                ->db
                ->select('students.stu_id, (SELECT COUNT(*) FROM students AS s2 WHERE s2.run_scr > s1.run_scr)
                            +1 AS rank FROM students AS s1')
                ->get('students');

运行代码会导致此错误:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL         
server version for the right syntax to use near 'FROM (`students`)' at line 3

SELECT `students`.`stu_id`, (SELECT COUNT(*) FROM students AS s2 WHERE s2.run_scr >    
s1.run_scr) +1 AS rank FROM students AS s1 FROM (`students`)

Filename: /home2/uder/public_html/scorer/models/get_score.php

Line Number: 78    

我非常感谢有关如何理顺这一点或提出更好解决方案的任何指导。

1 个答案:

答案 0 :(得分:0)

使用活动记录编写排名查询的方式是错误的尝试

$query = $this->db
              ->select('s1.stu_id,
              (SELECT COUNT(*) FROM students AS s2 WHERE s2.run_scr > s1.run_scr) +1 AS `rank`' ,
                      FALSE)
              ->get('students s1');

$query = $this->db
              ->select('s1.stu_id,
              (SELECT COUNT(*) FROM students AS s2 WHERE s2.run_scr > s1.run_scr) +1 AS `rank`' ,
                      FALSE)
              ->from('students s1')
              ->get();