Mysql query problem

后端 未结 8 833
逝去的感伤
逝去的感伤 2020-12-22 03:24

I have a problem with my mysql query.

My database:

sections
id
section_name

grades
id
user_id
section_id
date
grade

I want my data

相关标签:
8条回答
  • 2020-12-22 04:08

    If I understand correctly:

    SELECT grades.*,sections.* 
      FROM grades INNER JOIN sections ON sections.id = grades.section_id 
      WHERE user_id=$id  ORDER BY grades.date DESC LIMIT 1
    
    0 讨论(0)
  • 2020-12-22 04:16

    I would pre-query based on the specific user_id you wanted, and find their max date per section.. Then, re-join back to sections and grades (now that this prequery will extremely limit the result set to join against). Then get section name and finally proper grade for the date matching the specific student (user) taking the course.

    select STRAIGHT_JOIN
          PreQuery.Section_ID,
          Sections.section_name,
          PreQuery.LastDatePerSection
       from
          ( select section_id, 
                   user_id,
                   max( date ) as LastDatePerSection 
                from
                   grades
                where
                   user_id = YourUserIDParameter
                group by
                   section_id ) PreQuery
    
          join sections
             on PreQuery.Section_ID = Sections.ID
    
          join grades
             on PreQuery.Section_ID = grades.Section_ID
             AND PreQuery.User_ID = grades.User_ID
             AND PreQuery.LastDatePerSection = grades.Date
    
    0 讨论(0)
提交回复
热议问题