MySQL:“排序依据”在“group by”内部

发布于 2024-10-24 07:36:11 字数 596 浏览 4 评论 0原文

我有一个names的MySQL表,它由两个字段组成:namerankname 值不是唯一的,可以有多个匹配项。

问题:我想选择按 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 BY name
ORDER BY rank 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤云独去闲 2024-10-31 07:36:11

您需要一个名为 聚合函数 max:

select name, max(rank)
  from names
 group by name;

通过这种方式,您将检索所有不同的名称,每个名称都与其最大排名相关联。

You need an aggregate function called max:

select name, max(rank)
  from names
 group by name;

This way you will retrieve all distinct names, each one associated with its max rank.

暖风昔人 2024-10-31 07:36:11

对我来说,它已经起作用:

要获取组内的最后一行:

select * from 
( select name, rank from names order by rank desc ) as a 
group by name

For me it has been worked:

To take the last row inside a group:

select * from 
( select name, rank from names order by rank desc ) as a 
group by name
合约呢 2024-10-31 07:36:11

使用 max():

select name,
       max(rank)
from names
group by name
order by max(rank) desc

Use max():

select name,
       max(rank)
from names
group by name
order by max(rank) desc
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文