MySQL:“排序依据”在“group by”内部
我有一个names
的MySQL表,它由两个字段组成:name
和rank
。 name
值不是唯一的,可以有多个匹配项。
问题:我想选择按 name
分组的记录,但如果有多个 name
,则应选择具有最高 rank
的记录被采取。
示例:
汤姆 2
本 1
本 2
从
排序名称
中选择*按名称
分组 按排名
DESC
通常返回:
Tom 2
Ben 1
我需要:
Tom 2
Ben 2
因为有两个 Ben,但第二个具有更高的等级。
看起来,MySQL 分组采用第一个名称并忽略其余的名称。
如何对“group by”内的记录进行排序,以便在有多个具有相同名称
的情况下确定应该采用哪条记录?
I have a MySQL table of names
, which consists of two fields: name
and rank
. The name
value is not unique can have multiple matches.
The problem: I want to select records, grouped by name
, but if there are more than one name
, the one with the highest rank
should be taken.
An example:
Tom 2
Ben 1
Ben 2
SELECT * FROM
names
GROUP BYname
ORDER BYrank
DESC
Usually returns:
Tom 2
Ben 1
I need:
Tom 2
Ben 2
Since there are two Bens, but the second one with a higher rank.
It seems, that MySQL grouping takes the first name and ignores the rest.
How do I order records inside "group by", so I could say which record should be taken, if there is more than one with the same name
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要一个名为
的聚合函数 max:
通过这种方式,您将检索所有不同的名称,每个名称都与其最大排名相关联。
You need an aggregate function called
max
:This way you will retrieve all distinct names, each one associated with its max rank.
对我来说,它已经起作用:
要获取组内的最后一行:
For me it has been worked:
To take the last row inside a group:
使用 max():
Use
max()
: