MySQL的最大计数只有几个最大

时间:2018-08-06 19:12:19

标签: mysql database join count max

我正在寻找一个查询,只得到最大的查询。

SELECT results.playerid, 
       username, 
       Count(*) AS count 
FROM   results 
       LEFT JOIN players 
              ON results.playerid = players.playerid 
WHERE  points = 5 
GROUP  BY playerid 
ORDER  BY count DESC 

结果:

+-----------+-----------+-------+
| playerID  | username  | count |
+-----------+-----------+-------+
| 1         | Lorem     | 2     |
| 2         | Ipsum     | 2     |
| 3         | Dolor     | 1     |
+-----------+-----------+-------+

预期输出:

+-----------+-----------+-------+
| playerID  | username  | count |
+-----------+-----------+-------+
| 1         | Lorem     | 2     |
| 2         | Ipsum     | 2     |
+-----------+-----------+-------+

如果只有最大的一个,那就没问题了。

有什么提示吗?

小提琴:http://sqlfiddle.com/#!9/7c74c17/1

1 个答案:

答案 0 :(得分:-1)

首先,您需要找出group by

的最大值是多少。
SELECT Count(players.playerid) AS count 
FROM   results 
       LEFT JOIN players 
              ON results.playerid = players.playerid 
WHERE  points = 5
GROUP  BY players.playerid
ORDER  BY count DESC
LIMIT 1;

然后您使用该查询过滤所需的结果。

SQL DEMO

SELECT results.playerid, 
       username, 
       Count(players.playerid ) AS count 
FROM   results 
       LEFT JOIN players 
              ON results.playerid = players.playerid 
WHERE  points = 5 
GROUP  BY playerid 
HAVING COUNT(players.playerid) = (
          SELECT Count(players.playerid) AS count 
          FROM   results 
                 LEFT JOIN players 
                        ON results.playerid = players.playerid 
          WHERE  points = 5
          GROUP  BY players.playerid
          ORDER  BY count DESC
          LIMIT 1
);

输出

| playerid | username | count |
|----------|----------|-------|
|        1 |    Lorem |     2 |
|        2 |    Ipsum |     2 |