在 mysql 查询中对结果进行排名时如何处理关系?我在这个例子中简化了表名和列,但它应该能说明我的问题:
SET @rank=0;
SELECT student_names.students,
@rank := @rank +1 AS rank,
scores.grades
FROM student_names
LEFT JOIN scores ON student_names.students = scores.students
ORDER BY scores.grades DESC
所以想象上面的查询产生:
Students Rank Grades
=======================
Al 1 90
Amy 2 90
George 3 78
Bob 4 73
Mary 5 NULL
William 6 NULL
尽管艾尔和艾米的成绩相同,但其中一个的排名高于另一个。艾米被骗了。我怎样才能使 Amy 和 Al 具有相同的排名,使他们都有 1 的排名。另外,William 和 Mary 没有参加测试。他们打包上课,在男孩的房间里抽烟。他们应该并列最后一名。
正确的排名应该是:
Students Rank Grades
========================
Al 1 90
Amy 1 90
George 2 78
Bob 3 73
Mary 4 NULL
William 4 NULL
如果有人有任何建议,请告诉我。