我正在使用一个存储学生的系统'每当学生重新提交他/她的答案时,通过创建新条目来回答表格中的问题。我只想要最后的答案。我已经在这里查看了一些最好的每组的帖子,并试图应用其中一些查询,但他们还没有产生我希望的结果。我得到的最接近的是获得最近一个问题的最新答案,但我需要回答学生回答的每个问题。下面是我到目前为止最接近的。
select t1.* from response_history as t1
LEFT OUTER JOIN response_history as t2
ON t1.student_id = t2.student_id
AND (t1.`date` > t2.`date`
OR (t1.`date` = t2.`date` AND t1.id > t2.id))
where t2.student_id IS NULL;
答案 0 :(得分:0)
经过一些试验和错误并看一眼this回答后,我能够提出这个似乎正常工作的查询。
SELECT t1.* FROM response_history t1
INNER JOIN (SELECT t2.student_id, t2.session_question_id, MAX(`date`) as `date`
FROM response_history t2
group by session_question_id, student_id) as groupedt2
ON t1.student_id = groupedt2.student_id and t1.`date` = groupedt2.`date`
答案 1 :(得分:0)
这与SQL Select only rows with Max Value on a Column中的大多数答案一样,您只需分组并加入学生ID和问题ID。
SELECT t1.*
FROM response_history AS t1
JOIN (SELECT student_id, session_question_id, MAX(date) AS date
FROM response_history
GROUP BY student_id, session_question_id) AS t2
ON t1.student_id = t2.student_id
AND t1.session_question_id = t2.session_question_id
AND t1.date = t2.date