MySQL - 生成的行号不是连续的

时间:2015-01-08 05:00:46

标签: mysql sequential row-number

我正在尝试为从我的数据库中选择的每一行生成行号,但似乎行号在排列之前遵循表的顺序(按顺序排列)。

实际表格 https://www.dropbox.com/s/otstzak20yxcgt6/test1.PNG?dl=0

查询后 https://www.dropbox.com/s/i9jaoy04vq6u2zh/test2.PNG?dl=0

代码

SET @row_num = 0; 
SELECT @row_num := @row_num + 1 as Position, Student.Stud_ID, Student.Stud_Name, Student.Stud_Class, SUM(Grade.Percentage) AS Points 
FROM Student, Student_Subject, Grade 
WHERE Student.Stud_ID = Student_Subject.Stud_ID 
AND Student_Subject.Stud_Subj_ID = Grade.Stud_Subj_ID 
AND Student.Stud_Form = '1' 
AND Grade.Quarter = '1' 
GROUP BY Student.Stud_ID 
ORDER BY Points DESC

请帮助。期待收到yall的回复。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试内部选择,因此行号将在ORDER BY之后生成,如下所示:

SET @row_num = 0; 
SELECT @row_num := @row_num + 1 as Position, s.* 
FROM
(
    SELECT
        Student.Stud_ID, Student.Stud_Name, Student.Stud_Class, SUM(Grade.Percentage) AS Points 
    FROM Student, Student_Subject, Grade 
    WHERE Student.Stud_ID = Student_Subject.Stud_ID 
        AND Student_Subject.Stud_Subj_ID = Grade.Stud_Subj_ID 
        AND Student.Stud_Form = '1' 
        AND Grade.Quarter = '1' 
    GROUP BY Student.Stud_ID 
    ORDER BY Points DESC
) AS s;