Mysql query problem

后端 未结 8 970
逝去的感伤
逝去的感伤 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 03:57

    If I get this right you want the latest grade per section. This cannot be done simply with MySQL.

    You'd need a window function or a sequence generator, neither of which are available in MySQL. There is a workaround using variables, however. See this question for a similar use-case:

    MySQL query: Using UNION and getting row number as part of SELECT

    Additional background information here:

    SQL/mysql - Select distinct/UNIQUE but return all columns?

    What you'll likely end up doing is a big nested query that will look like this:

    select t.*
    from (select @rownum := @rownum + 1 rownum,
                 t.*
          from (select *
                  from grades join sections on sections.id = grades.section_id 
                 where user_id=$id order by grades.date desc
               ) t,
               (select @rownum := 0) r
          ) t
    where t.rownum = 1
    

提交回复
热议问题