mysql 在分组前排序

标签 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条记录?

最佳答案

使用:

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

关于mysql 在分组前排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930965/

相关文章:

PHP 在从数据库中输入 NULL 值的下拉列表中显示空白值

mysql - SQL左连接和group_concat返回重复数据

postgresql - postgres 按行聚合子集

sql - Postgres : limit by the results of a sum function

sql - 更新零行然后提交?

postgresql - 复杂连接上的重复数组

mysql - 使用 Rails 应用程序中存在于多个数据库中的表

mysql - 存储过程中出现意外的逗号

php - 使用 PDO 省略 bindParam 安全吗?

sql - 唯一 ID 的连续行中的值之间的差异