选择不在“小组”子句中的列的选项?
我是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
典型的解决方案是使用
row_number()
识别所需的行。例如:
The typical solution is to use
ROW_NUMBER()
to identify the rows you want.For example: