求每个人相同试卷成绩最好的那条记录,如果最高成绩有相同的,获取最近的那条记录
考试成绩表,exam
| id | papge_id | user_id | score | created_at |
| -主键- | -试卷id- | -用户id- | -成绩- | --考试日期-- |
| 1 | 1 | 4 | 80 | 2022-09-01 |
| 2 | 1 | 4 | 90 | 2022-09-02 |
| 3 | 1 | 4 | 90 | 2022-09-03 |
| 1 | 1 | 4 | 80 | 2022-09-04 |
| 4 | 1 | 5 | 70 | 2022-09-01 |
| 5 | 1 | 5 | 50 | 2022-09-02 |
| 6 | 1 | 5 | 55 | 2022-09-03 |
| 7 | 1 | 6 | 55 | 2022-09-01 |
| 8 | 1 | 6 | 60 | 2022-09-02 |
| 9 | 1 | 6 | 40 | 2022-09-03 |
sql:
select * from exam inner join (select user_id, max(score) as max from exam group by user_id) as high on high.user_id =exam.user_id
where exam.score=high.max and exam.paper_id =1
结果:
| 2 | 1 | 4 | 90 | 2022-09-02 |
| 3 | 1 | 4 | 90 | 2022-09-03 |
| 4 | 1 | 5 | 70 | 2022-09-01 |
| 8 | 1 | 6 | 60 | 2022-09-02 |
因为user_id=4时,最高分90有两条,所以返回时会出现两条记录,有什么办法可以获取id=3时的那条记录,
如何得到下面这样的结果,希望sql语句尽量的简短,用laravel上的方法更好
| 3 | 1 | 4 | 90 | 2022-09-03 |
| 4 | 1 | 5 | 70 | 2022-09-01 |
| 8 | 1 | 6 | 60 | 2022-09-02 |
MySQL:
结果(
r
没用):