测试数据准备
-- mybatis.student definition
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO mybatis.student
(id, name, email, age, score)
VALUES(1, 'zs', 'aaa', 12, 98);
INSERT INTO mybatis.student
(id, name, email, age, score)
VALUES(2, 'b', 'bbb', 13, 95);
INSERT INTO mybatis.student
(id, name, email, age, score)
VALUES(3, 'zs', 'zs', 13, 97);
INSERT INTO mybatis.student
(id, name, email, age, score)
VALUES(4, 'ee', 'dd', 14, 95);
错误答案
select name,score
from student
order by score desc
limit 3
SELECT
`name`,
score,
rank -- 表结构中不存在的字段
FROM
-- 表子查询
(SELECT
`name`,
score,
-- 定义排名变量
@rownum := @rownum + 1 AS tmp,
-- 用于记录排名的变量,将该变量作为brank列
@incrnum :=
-- case 使用方式二:多重if效果
CASE
-- 分数是否相同: 分数变量 是否等于 成绩列分数 分数相同: 将当前的 排名变量 赋值给rank变量
WHEN @rowtotal = score THEN @incrnum
-- 分数不同: 将分数列赋值给 分数变量 ,将当前排名赋值给rank变量
WHEN @rowtotal := score THEN @rownum
END AS rank
FROM
( SELECT id, `name`, score FROM student ORDER BY score DESC ) AS a,
( SELECT @rownum := 0, @rowtotal := NULL, @incrnum := 0 ) b ) c
WHERE
rank <= 3