MySQL中处理排序问题
#关键#
1、利用“条件判断”获取比当前年龄大的“个数”(子查询);
2、根据“连续/不连续“的要求,选择distinct。
(注意:如果使用了DISTINCT,是将所有相同的归为一个,因此会连续)
一、相同的年龄,排名相同,排名连续
SELECT s1.学号 as no,(SELECT COUNT(DISTINCT(`年龄`)) FROM student WHERE `年龄`>=s1.`年龄`) as r
FROM student s1 LEFT JOIN student s2 ON s1.`学号`=s2.`学号`
二、相同的年龄,排名相同;排名不连续
SELECT s1.学号 as no,((SELECT COUNT(`年龄`) FROM student WHERE `年龄`>s1.`年龄`)+1) as r
FROM student s1 LEFT JOIN student s2 ON s1.`学号`=s2.`学号`
注意:这样会错误
SELECT s1.学号 as no,(SELECT COUNT(`年龄`) FROM student WHERE `年龄`>=s1.`年龄`) as r
FROM student s1 LEFT JOIN student s2 ON s1.`学号`=s2.`学号`
第一个不受影响,但是接下的就会错误