首先表结构
create table sysstudentlibrarypool
(
id int auto_increment primary key,
score int null,
time varchar(255) null,
count int null,
classify int null,
stuId int null,
lpId int null,
)
- id为主键
- score是分数
- time是时间 (yyyy-MM-dd)
- count是次数
- classify是类别
- stuId是个外键指向学生表的学生id
- lpId是个外键指向关卡id
这张表用于保存学生每次完成关卡的分数
需求就是取每个学生在指定关卡的最大分数
加粗的就是与需求有关的字段
先排序后分组
select *
from (
select *
from sysstudentlibrarypool
order by score desc
) t
group by stuId
先根据分数排序,再根据 stuId 和 lpId 分组。
看这个逻辑貌似是很有道理
但执行了之后却好像并没有达到我所要的需求
虽然 学生与关卡分组了但是,并没有取到最大做题分数啊!
加个max()
select
id,
max(score) as score,
time,
count,
classify,
stuId,
lpId
from (
select *
from sysstudentlibrarypool
order by score desc
) t
group by stuId, lpId
额,的确是显示了最大的分数了,但是好像记录是对不上的
只显示了最大的分数其他的字段并不是对应分数的
实现思路
唉,找不到靠谱的轮子只能自己上了
select
id,
max(score) as score,
time,
count,
classify,
stuId,
lpId
from sysstudentlibrarypool
where 1 = 1 and stuId in (select distinct (stuId)
from sysstudentlibrarypool
where 1 = 1)
group by lpId, stuId
order by score desc;
主要实现思路:
1. 子查询中取 学生id(有条件时取单个,没有条件时取所有的学生id)
2. 根据关卡 学生id 分组,然后进行分数排序(取分数最大的),也可以添加各种条件(指定关卡,指定时间戳等)
3. 就能查询每关的每个学生的最大分数
这样每个where 1 = 1后面都能加上查询条件了。
积累
- 1.
group by
order by
这里的排序是对分组后的数据排序
2. 突然有点明白group by的作用了
对指定的字段进行分组,然后根据需求显示,想要的字段,比如每组中max(某字段)
不知道怎么的以前总理解为 分组并显示每组中所有记录。。。。。
这里只是提供一下自己的思路,也请大神给出更好的实现,相互学习,谢谢。