MYSQL:Select 最近一行有 2 列或更多列不同
MYSQL: Select most recent row with 2 or more columns distinct
我正在使用一个系统,该系统通过在学生每次重新提交 his/her 答案时创建一个新条目来将学生对问题的回答存储在 table 中。不过我只想要最后的答案。我查看了这里的一些 greatest-n-per-group 帖子,并尝试应用其中的一些查询,但它们还没有产生我希望的结果。我得到的最接近的是得到最近问题的最新答案,但我需要学生回答的每个问题的答案。以下是我目前得到的最接近的。
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;
经过更多的尝试和错误并查看 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`
这与 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
我正在使用一个系统,该系统通过在学生每次重新提交 his/her 答案时创建一个新条目来将学生对问题的回答存储在 table 中。不过我只想要最后的答案。我查看了这里的一些 greatest-n-per-group 帖子,并尝试应用其中的一些查询,但它们还没有产生我希望的结果。我得到的最接近的是得到最近问题的最新答案,但我需要学生回答的每个问题的答案。以下是我目前得到的最接近的。
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;
经过更多的尝试和错误并查看 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`
这与 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