首页 > 解决方案 > 如何在 mysql 中结合 GROUP BY 和 MAX 以获取具有字段最大值的完整记录?

问题描述

我有一个表'wordstyped',其中包含'idBook'、'guidUser'、'bookmarkLetter'、'letter'和'attemptWrong'。

idBook  guidUser  bookmarkLetter  letter  attemptWrong
------------------------------------------------------
1       1         100             a       2
1       1         100             a       3
1       1         101             b       6
2       2         101             b       2
2       2         101             b       3
2       2         152             d       7
3       3         153             e       2

我想选择所有记录,其所有字段包含最大数量的“attemptWrong”,但不同的三元组“idBook”、“guidUser”和“bookmarkLetter”。我想我可以通过正确使用 GROUP BY 和 MAX 运算符来达到这个结果。期望的结果是:

idBook  guidUser  bookmarkLetter  letter  attemptWrong
------------------------------------------------------
1       1         100             a       3
1       1         101             b       6
2       2         101             b       3
2       2         152             d       7
3       3         153             e       2

我可以通过此查询获得最大尝试

SELECT *,MAX(attemptWrong) as maxAttemptWrong FROM wordstyped GROUP BY idBook, guidUser, bookmarkLetter

但它返回

idBook  guidUser  bookmarkLetter  letter  attemptWrong  maxAttemptWrong
-----------------------------------------------------------------------
1       1         100             a       2             3
1       1         101             b       6             6
2       2         101             b       2             3
2       2         152             d       7             7
3       3         153             e       2             2

就像在这个小提琴http://sqlfiddle.com/#!9/135cf9/1

所以它返回正确的 maxAttemptWrong,但不是正确的记录。我错过了什么?

标签: mysql

解决方案


我相信您将需要某种子查询来执行此操作,即使您使用的是分析函数。使用 MySQL 8 之前的方法,我们可以将您的wordstyped表连接到一个子查询,该查询可以找到每个书签字母的最大错误尝试次数。这将原始表限制为仅在最终输出中需要的匹配行。

SELECT w1.*
FROM wordstyped w1
INNER JOIN
(
    SELECT bookmarkLetter, guidUser, MAX(attemptWrong) AS maxAttemptWrong
    FROM wordstyped
    GROUP BY bookmarkLetter, guidUser
) w2
    ON w1.bookmarkLetter = w2.bookmarkLetter AND
       w1.guidUser = w2.guidUser AND
       w1.attemptWrong = w2.maxAttemptWrong;

推荐阅读