仅获取用户关于练习 _id 的最后一次 trynumber 报告

Get reports only last trynumber report of user on exercise _id

希望你一切都好

如果有人可以帮助我,我需要 MYSQL 我使用 Laravel 但直接 SQL 对我来说是一样的 :(

我有一份报告 table,其中包含列

-id
-exercise_id (example 1 is not a foreign key since the exercises are not known)
-try_number (user attempt number)
-fk_student (foreign key of a student)

我需要得到所有的报告(但每个学生只有 1 个并且 exercise_id 并且只有最高 try_number 的报告)

例如,如果我有这个数据:

ID: 1
Exercise_ID: 1
TryNumber: 1
FK_Student: 1

ID: 2
Exercise_ID: 1
TryNumber: 2
FK_Student: 1

ID: 3
Exercise_ID: 1
TryNumber: 1
FK_Student: 2

ID: 4
Exercise_ID: 1
TryNumber: 2
FK_Student: 2

ID: 5
Exercise_ID: 1
TryNumber: 3
FK_Student: 2

ID: 6
Exercise_ID: 2
TryNumber: 1
FK_Student: 1

ID: 7
Exercise_ID: 2
TryNumber: 2
FK_Student: 1

我想得到以下信息:

ID: 2
Exercise_ID: 1
TryNumber: 2
FK_Student: 1

ID: 5
Exercise_ID: 1
TryNumber: 3
FK_Student: 2

ID: 7
Exercise_ID: 2
TryNumber: 2
FK_Student: 1

我尝试分组,但我感到困惑:(

我评论这个SQL select only rows with max value on a column [duplicate] 但我无法理解如何在必要时添加 where 和 group,因为这 (但每个学生只有 1 个并且 exercise_id 并且只有最高 try_number 的报告)

我有这个SQL

select * from `reports`
where unity_try_number = (select max(`unity_try_number`) from reports)
group by `fk_student`, `unity_exercise_id`

但我不知道如何在子查询上添加实际 fk_student 和实际 exercise_id 的位置(select max(unity_try_number) 来自报告)

非常感谢!您好!

使用相关子查询:

select r.*
from reports r
where r.unity_try_number = (select max(r2.unity_try_number)
                            from reports r2
                            where r2.fk_student = r.fk_student and
                                  r2.unity_exercise_id = r.unity_exercise_id
                           );