mysql在g​​roup by之前排序

时间:2011-05-08 23:03:08

标签: mysql sql aggregate-functions

我认为这是best solution。但是,这个查询并没有解决我的问题 - 我喜欢这个表:

+--+-------+-----+
|id|user_id|score|
+--+-------+-----+
|1 |1      |5    |
+--+-------+-----+
|2 |1      |16   |
+--+-------+-----+
|3 |1      |15   |
+--+-------+-----+

查询:

  SELECT *
    FROM (`_scorboard`)
GROUP BY `user_id`
  HAVING `score` = MAX(score)
ORDER BY `score` desc 

result 0 rows

为什么返回0条记录?

2 个答案:

答案 0 :(得分:3)

使用:

SELECT a.*
  FROM SCOREBOARD a
  JOIN (SELECT t.user_id,
               MAX(t.score) AS max_score
          FROM SCOREBOARD t
      GROUP BY t.user_id) b ON b.max_score = a.score
                           AND b.user_id = a.user_id

如果你想要那些得分最高的人:

SELECT a.*
  FROM SCOREBOARD a
  JOIN (SELECT MAX(t.score) AS max_score
          FROM SCOREBOARD t) b ON b.max_score = a.score

答案 1 :(得分:3)

由于您的查询中有GROUP BY子句,MySQL首先user_id 1分组,然后选择它喜欢的任何行。然后HAVING子句适用于这些选定的行。由于所选行可能是MAX值为score的行,也可能不是 SELECT _scoreboard.* FROM _scoreboard JOIN (SELECT user_id, MAX(score) FROM _scorboard GROUP BY user_id) AS t ON _scoreboard.user_id = t.user_id AND _scoreboard.score = t.score ORDER BY _scoreboard.score DESC 值,因此查询返回0结果。

正确的做法是:

{{1}}