思路
1.首先根据班级分组获取每个班级的所有学生并通过成绩排序
2.过滤掉不符合条件的学生 最终获取所有符合条件的学生
3.在通过学生唯一字段获取学生信息
需要用到mysql下面几个函数
GROUP_CONCAT 可以把结果集中的多行中特定数据显示成一列数据
FIND_IN_SET 可以查看字串序列list(多个字串用逗号分隔)是否包含字串str 可以通过 BETWEEN AND 来指定使用哪些字串 如FIND_IN_SET("ww","www,fff,kk") between 2 and 3 等于 FIND_IN_SET("ww","fff,kk") 所以结果为false
SUBSTRING_INDEX 可以通过某个字符来分隔字串获取前几个子串
建立测试数据
DROP TABLE `student_score` ;
CREATE TABLE `student_score` (
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名' ,
`class` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '班级' ,
`score` int(10) NOT NULL COMMENT '分数' ,
PRIMARY KEY (`class`, `name`)
);
INSERT INTO student_score
VALUES
('张三',"一年级",33),('张四',"一年级",44),('张五',"一年级",74),('张六',"一年级",80),('张七',"一年级",90),('张八',"一年级",100),
('李三',"二年级",33),('李四',"二年级",44),('李五',"二年级",74),('李六',"二年级",80),('李七',"二年级",90),('李八',"二年级",100),
('王三',"三年级",33),('王四',"三年级",44),('王五',"三年级",74),('王六',"三年级",80),
('赵三',"四年级",33),('赵四',"四年级",44),('赵五',"四年级",74),
('燕三',"五年级",33);
查询出班级成绩前三名的同学
#方式一
SELECT s.* FROM student_score s,
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(name ORDER BY score DESC),",",3) as names
FROM student_score s GROUP BY class
) as d
WHERE FIND_IN_SET(s.name,d.names) BETWEEN 1 AND 3
ORDER BY class,score desc;
#方式二
SELECT * FROM student_score WHERE FIND_IN_SET(name,
(SELECT GROUP_CONCAT(NAMES) as names FROM
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(name ORDER BY score DESC),",",3) as names
FROM student_score s GROUP BY class
) as d
)
) ORDER BY class,score desc
查询出班级成绩第2名到第六名的同学
SELECT s.* FROM student_score s,
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(name ORDER BY score DESC),",",6) as names
FROM student_score s GROUP BY class
) as d
WHERE FIND_IN_SET(s.name,d.names) BETWEEN 2 AND 6
ORDER BY class,score desc;