SQL帮助:为每个学生选择最后3条注释?

SQL帮助:为每个学生选择最后3条注释?,sql,mysql,Sql,Mysql,我有两个表来存储小学教室的学生数据: 行为日志包含学生id、评论、日期等列 学生名册中有“学生id”、“姓氏”和“姓氏”列 该数据库用于存储有关学生行为的每日评论,有时教师会在给定的一天内对一名学生发表多条评论 现在让我们假设老师希望能够为每个学生列出最后3条评论,如下所示: Jessica 7/1/09 talking Jessica 7/1/09 passing notes Jessica 5/3/09 absent Ciboney 7/2/09 great participation Ci

我有两个表来存储小学教室的学生数据:

行为日志包含学生id、评论、日期等列 学生名册中有“学生id”、“姓氏”和“姓氏”列

该数据库用于存储有关学生行为的每日评论,有时教师会在给定的一天内对一名学生发表多条评论

现在让我们假设老师希望能够为每个学生列出最后3条评论,如下所示:

Jessica 7/1/09 talking
Jessica 7/1/09 passing notes
Jessica 5/3/09 absent
Ciboney 7/2/09 great participation
Ciboney 4/30/09 absent
Ciboney 2/22/09 great participation
……全班同学都是如此

单个SQL查询必须为每个学生返回一组注释,以消除教师为班级中每个学生运行单独查询所需的大量人力

我知道这听起来很像 但我需要为每个人显示最后3个条目,我不知道如何从这里到那里


谢谢你的建议

我的博客中这篇文章中的一个稍加修改的解决方案:


另一种方法是使用group_concat函数和单个子选择以及对该子选择的限制

select (
     select group_concat( concat( student, ', ', date,', ', comment ) separator '\n' )
       from Behavior_Log 
      where student_id = s.student_id
   group by student_id
      limit 3 )
  from Student_Roster s
select (
     select group_concat( concat( student, ', ', date,', ', comment ) separator '\n' )
       from Behavior_Log 
      where student_id = s.student_id
   group by student_id
      limit 3 )
  from Student_Roster s