MySQL中group by语句后选择对应的非聚合列

Pra*_*anD 5 mysql sql aggregate-functions

我有一个从更大的表派生出来的临时表。

+-----+----------+---------+
| id  | phone    | attempt |
+-----+----------+---------+
|  1  | 12345678 |      15 |
|  2  | 87654321 |       0 |
|  4  | 12345678 |      16 |
|  5  | 12345678 |      14 |
|  10 | 87654321 |       1 |
|  11 | 87654321 |       2 |
+-----+----------+---------+
Run Code Online (Sandbox Code Playgroud)

我需要找到与每个电话号码上的最高尝试相对应的 ID(唯一)。电话和尝试并不是独一无二的。

SELECT id, MAX(attempt) FROM temp2 GROUP BY phone
Run Code Online (Sandbox Code Playgroud)

上述查询不会返回相应最大尝试次数的 ID。

Gur*_*ngh 3

尝试这个:

select
    t.*
from temp2 t
inner join (
    select phone, max(attempt) attempt
    from temp2
    group by phone
) t2 on t.phone = t2.phone
and t.attempt = t2.attempt;
Run Code Online (Sandbox Code Playgroud)

它将返回给定数量的最大尝试次数的行。

请注意,如果电话有多个行且尝试次数与该电话的最大尝试次数相同,则这将返回多个 id。

演示在这里