如何根据2条标准获取记录

时间:2018-10-09 10:39:01

标签: mysql sql database

我想根据得分最高和花费最少的时间来获得记录

SELECT user.id, user.first_name, user.last_name, quiz.id, quiz.name, user_quiz_history.score, user_quiz_history.time_taken
FROM user_quiz_history
JOIN user ON user.id = user_quiz_history.user_id
JOIN quiz ON quiz.id = user_quiz_history.quiz_id WHERE score =
    (SELECT MAX(score)
    FROM user_quiz_history
    WHERE quiz_id = $id)
GROUP BY quiz_id
ORDER BY quiz_id dESC

通过此查询,我得到了预期的结果,但仅使用MAX(分数)。

在某些情况下,分数相等,所以我不得不根据花费的时间更少来进行区分。

在这种情况下,它会拾取两条相同分数但time_taken不同的记录中的第一条记录。

1 个答案:

答案 0 :(得分:0)

您可以在子查询中按得分和时间排序,并限制为1

SELECT ...
JOIN quiz ON quiz.id = user_quiz_history.quiz_id
WHERE user_quiz_history.id =
    (SELECT qh.id
    FROM user_quiz_history qh
    WHERE qh.quiz_id = $id
    ORDER BY qh.score DESC,
             qh.time_taken ASC
    LIMIT 1)
...;