Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

MySql subqueries and max or group by?

I have this table:

ID STUDENT CLASS QUESTION ANSWER   TIME
 1   1      1       1       c     12:30
 2   1      1       1       d     12:36
 3   1      1       2       a     12:38
 4   2      1       1       b     11:24
 5   2      1       1       c     11:26
 6   2      1       3       d     11:35
 7   2      3       3       b     11:24

I'm trying to write a query that does this:

For each STUDENT in a specific CLASS select the most recent ANSWER for each QUESTION.

So, choosing class "1" would return:

ID STUDENT CLASS QUESTION ANSWER   TIME
 2   1      1       1       d     12:36
 3   1      1       2       a     12:38
 5   2      1       1       c     11:26
 6   2      1       3       d     11:35

I've tried various combinations of subqueries, joins, and grouping, but nothing is working. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a sub-query to get most recent ANSWER per QUESTION, Then use this as a derived table and join back to the original table:

 SELECT m.*
 FROM mytable AS m
 INNER JOIN (
    SELECT STUDENT,  QUESTION, MAX(`TIME`) AS mTime
    FROM mytable
    WHERE CLASS = 1
    GROUP BY STUDENT, QUESTION 
) AS d ON m.STUDENT = d.STUDENT AND m.QUESTION = d.QUESTION AND m.`TIME` = d.mTime
WHERE m.CLASS = 1

Demo here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...