MySQL 子查询——查询最大值


       子查询指将一个查询语句嵌套在另一个查询语句中。子查询可以在 SELECT、UPDATE 和 DELETE 语句中使用,而且可以进行多层嵌套。在实际开发时,子查询经常出现在 WHERE 子句中。子查询在 WHERE 中的语法格式如下:
       WHERE <表达式> <操作符> (子查询)
       其中,操作符可以是比较运算符和 IN、NOT IN、EXISTS、NOT EXISTS 等关键字。

要求:查出指定范围的最大值,同时显示与之相关的其它信息
实例:查询全班最高分,查询全级最高分,查询全校最高分,同时显示最高分者的姓名,所在班级以及各科成绩情况。
1、查询全班最高分
mysql> select * from studscoreinfo
-> where total_scores = (select max(total_scores) from studscoreinfo where grade_classes =201);
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
| Id | Grade_Classes | Seat_Numbers | Names | Chinese_Scores | Math_Scores | English_Scores | Total_Scores | Score_Averages | Remarks |
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
| 22 | 201 | 5 | 陈炜涛 | 88 | 100 | 96 | 284 | 94.7 | |
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
1 row in set (0.00 sec)

2、查询全级最高分
mysql> select * from studscoreinfo
-> where total_scores = (select max(total_scores) from studscoreinfo where grade_classes between 101 and 102);
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
| Id | Grade_Classes | Seat_Numbers | Names | Chinese_Scores | Math_Scores | English_Scores | Total_Scores | Score_Averages | Remarks |
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
| 9 | 101 | 9 | 赖嘉欣 | 84 | 98 | 96 | 278 | 92.7 | |
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
1 row in set (0.00 sec)

3、查询全校最高分
mysql> select * from studscoreinfo
-> where total_scores = (select max(total_scores) from studscoreinfo where grade_classes between 301 and 302);
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
| Id | Grade_Classes | Seat_Numbers | Names | Chinese_Scores | Math_Scores | English_Scores | Total_Scores | Score_Averages | Remarks |
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
| 38 | 302 | 2 | 陈资彬 | 89.5 | 98 | 98.5 | 286 | 95.3 | |
+------+---------------+--------------+-----------+----------------+-------------+----------------+--------------+----------------+---------+
1 row in set (0.00 sec)

       第一行*是选所有列进行查询,全显示,也可根据需要指定列名查询,第二行中操作符前面的"="可用in代替,效果一样。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM