【做题杂记】类型题:查询第N高的数据'

现在有“课程表”,记录了学生选修课程的名称以及成绩。

现在需要找出语文课中成绩第二高的学生成绩。如果不存在第二高成绩的学生,那么查询应返回 null。


当遇到查找第二名时

思路一(不实用,只能找第二位):

1.找出所有选修了语文课的学生成绩

1
2
select * from grades
where class = "Chinese";

2.找出最高值

1
2
select max(distinct score) from grades
where class = "Chinese"

3.组合找出第二

1
2
3
4
5
6
7
select max(distinct score)
from grades
where class = "Chinese" and
score<(
select max(distinct score) from grades
where class = "Chinese"
)

思路2(普遍):

使用 limit 和 offset
limit n子句表示查询结果返回前n条数据

offset n表示跳过x条语句

limit y offset x 分句表示查询结果跳过 x 条数据,读取前 y 条数据

注意:limit x:y和offset不同
前者表示跳过x条数据读取y条数据

1
2
3
4
5
select distinct score
from grades
where class = "Chinese"
order by class,score desc
limit 1,1;

拓展:若没有第x名呢?

ifnull:
ifnull(a,b)函数解释:
如果value1不是空,结果返回a
如果value1是空,结果返回b

完善代码:

1
2
3
4
5
6
7
select ifnull(
(select max(distinct score) from grades
where class = "Chinese"
order by class,score desc
limit 1,1
),null
) as "the second score"

×

纯属好玩

扫码支持
谢谢你

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 现在有“课程表”,记录了学生选修课程的名称以及成绩。
  2. 2. 现在需要找出语文课中成绩第二高的学生成绩。如果不存在第二高成绩的学生,那么查询应返回 null。
  3. 3. 当遇到查找第二名时
    1. 3.1. 思路一(不实用,只能找第二位):
      1. 3.1.1. 1.找出所有选修了语文课的学生成绩
      2. 3.1.2. 2.找出最高值
      3. 3.1.3. 3.组合找出第二
    2. 3.2. 思路2(普遍):
    3. 3.3. 拓展:若没有第x名呢?
,