MYSQL如何查询成绩为前5名的学生
目录
- 需求:查询成绩为前5名的学生
- mysql查询
- 查询应用
- 查询成绩最高和最低的人
- 简单描述
- 思路
- 总结
需求:查询成绩为前5名的学生
拿到需求后,先对需求进行分析,找出筛选的条件
Mysql查询
1、最基本的查询
select * from table where name="panpan"
2、查前5名
在mysql中筛选数据的前几名,可以用关键字:limit
select * from table where name="panpan" limit 1
说明:查询表中名为panpan的第一条记录
3、以什么条件进行筛选,需求是以成绩进行筛选,则可以用order by 排序筛选
select * from table order by grade
查询应用
合并后查询:
select * from score order by grade limit 5
说明:查询到score表里的grade ,以grade筛选,提取出前5条记录
查询成绩最高和最低的人
简单描述
成绩表中有学生姓名、学生科目以及学生分数。查询分数最高和分数最低的xuhfSHu学生的以及学生的分数。注意的点如下:
1、group by,select 选择的列,必须是group by 中的列,或者是函数形式。
2、利用MAX() 和MIN()sql函数。
3、建立的表结构如下。
-- ---------------------------- http://www.devze.com-- Table structure for grade -- ---------------------------- DROP TABLE IF EXISTS `grade`; CREATE TABLE `grade` ( `stu_name` varchar(255) NOT NULL, `stu_subject` varchar(255) NOT NULL, `score` int(255) DEFAULT NULL, PRIMARY KEY (`stu_subject`,`stu_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of grade -- ---------------------------- INSERT INTO `grade` VALUES ('lilei', 'shuxue', '99'); INSERT INTO `grade` VALUES ('xiaoyong', 'shuxue', '66'); INSERT INTO `grade` VALUES ('lilei', 'yingyu', '80'); INSERT INTO `grade` VALUES ('xiaoyong', 'yingyu', '55'); INSERT INTO `grade` VALUES ('lilei', 'yuwen', '78'); INSERT INTO `grade` VALUES ('xiaoyong', php'yuwen', '88');
思路
1) 按照科目分组查询成绩最高的人
SELECT grade.stu_subject, MAX(grade.score) as score from grade GROUP BY stu_subject;
2) 显示出成绩最高的人的姓名和科目名称
SELECT grade.* from grade, (SELECT grade.stu_subject, MAX(grade.score) as score from grade GROUP BY stu_subject )b WHERE grade.score = b.score and grade.stu_subject = b.stu_subject;
3) 显示出列标题.
SELECT “成绩最高”,grade.* from grade, (SELECT grade.stu_subject, MAX(grade.score) xuhfSHuas score from grade GROUP BY stu_subject )b WHERE grade.score = b.score and grade.stu_subject = b.stu_subject;
成绩最低的也是如此就是利用MIN()函数, 如果需要同时查出, 可以用union 如下sql
SELECT "成绩最高",grade.* from grade, (SELECT grade.stu_subject, MAX(grade.score) as score from grade GROUP BY stu_subject )b WHERE grade.score = b.score and grade.stu_subject = b.stu_subject UNION SELECT "成绩最低",grade.* from grade, (SELECT grade.stu_subject, MIN(grade.score) as scphpore from grade GROUP BY stu_subject )b WHERE grade.score = b.score and grade.stu_subject = b.stu_subject;
查询结果如下图所示:
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
精彩评论