mysql在分组之前排序
Posted
技术标签:
【中文标题】mysql在分组之前排序【英文标题】:mysql sort before group by 【发布时间】:2011-08-21 07:38:49 【问题描述】:我认为这是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 * ... GROUP BY ...
是一件很奇怪的事情!
here,这样的解决方案是由
我是这样解决的,但我认为这不是正确的解决方案 SELECT t1.*, CONCAT(t2.firstname, ' ', t2.lastname) AS fullname FROM (SELECT * FROM _scorboard ORDER BY score DESC) AS t1 LEFT JOIN _user_profile AS t2 ON(t1.user_id = t2.user_id) GROUP BY t1.user_id LIMIT 0, 20
【参考方案1】:
用途:
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
【讨论】:
【参考方案2】:由于您的查询中有GROUP BY
子句,mysql 首先按1
的user_id
分组,选择它喜欢的任何行。然后HAVING
子句适用于这些选定的行。由于所选行可能是也可能不是 MAX
值为 score
的行,因此查询返回 0 个结果。
正确的做法是:
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
【讨论】:
感谢您实际回答问题!这是我从中学到的解决方案! :)以上是关于mysql在分组之前排序的主要内容,如果未能解决你的问题,请参考以下文章