选择不在“小组”子句中的列的选项?

发布于 2025-02-10 11:11:14 字数 898 浏览 0 评论 0原文

我是SQL的初学者。我有以下“动物”桌子:

RACE  NAME   AGE
dog   Medor  10
dog   Arthur 17
dog   Pitou  9
cat   Kitty  11
cat   Milo   5
cat   Loki   7
dog   Jack   14

我想编写一个查询,以获取每个种族的最高年龄以及相关动物的名称。我尝试过:

SELECT race, name, MAX(age) FROM animal GROUP BY race

它确实执行了每场比赛的分组,并且确实返回了每个种族的最高年龄,但是,每个种族中动物的名称似乎是随机的。基本上,它返回,

RACE  NAME   MAX(age)
dog   Medor  17
cat   Kitty  11

而我希望它能返回

RACE  NAME   MAX(age)
dog   Arthur 17
cat   Kitty  11

,我读到有关_full_group_by的阅读,并理解SQL将选择“名称列”的任何值,而我希望它可以选择与最大年龄相关的值。

我唯一可以想象的是做一个子问题,但这似乎很复杂。

SELECT race, name, age FROM animal B WHERE age = (SELECT MAX(age) FROM animal A WHERE A.race = B.race)

我很惊讶没有更简单的解决方案。我有两个问题:

  • 首先,我的原始查询不应起作用(即产生预期结果)是否正确?
  • 有比做子查询更好的方法吗?

我正在使用mysql 8.x。

I am a beginner in SQL. I have the following 'animal' table:

RACE  NAME   AGE
dog   Medor  10
dog   Arthur 17
dog   Pitou  9
cat   Kitty  11
cat   Milo   5
cat   Loki   7
dog   Jack   14

I want to write a query to get the maximum age of each race, as well as the name of the associated animal. I tried:

SELECT race, name, MAX(age) FROM animal GROUP BY race

It does perform the per-race grouping, and does return the maximum age of each race, however, the name of the animal in each race seems random. Basically, it returns

RACE  NAME   MAX(age)
dog   Medor  17
cat   Kitty  11

whereas I would like it to return

RACE  NAME   MAX(age)
dog   Arthur 17
cat   Kitty  11

I read about ONLY_FULL_GROUP_BY and understood SQL will select any value for the NAME column, whereas I expected it to select the value associated with the maximum age.

The only other way I can imagine would be to do a sub-query, but this seems very complicated.

SELECT race, name, age FROM animal B WHERE age = (SELECT MAX(age) FROM animal A WHERE A.race = B.race)

I am surprised there is not a simpler solution. I have two questions:

  • is it correct my original query should not work (ie. produce the expected result) in the first place?
  • is there a better way than doing a subquery?

I'm using MySQL 8.x.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

指尖上得阳光 2025-02-17 11:11:14

典型的解决方案是使用row_number()识别所需的行。

例如:

select *
from (
  select a.*,
    row_number() over(partition by race order by age desc) as rn
  from animal a
) x
where rn = 1

The typical solution is to use ROW_NUMBER() to identify the rows you want.

For example:

select *
from (
  select a.*,
    row_number() over(partition by race order by age desc) as rn
  from animal a
) x
where rn = 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文