想请教下,怎么实现mysql这样的分组查询?
ringa_lee
ringa_lee 2017-04-17 13:35:05
[MySQL讨论组]

想请教下,这张表

自己用命令分组的话,结果却不正确了,

结果显示为qiu 42, (应该是liu 42),怎样这样显示出

自己写的
只能显示一个类别里的,怎样能显示所有类别里的最大年龄?
假如这样写的话 就是这样的截图了

ringa_lee
ringa_lee

ringa_lee

全部回复(3)
阿神

先排个序:

SELECT id, name, max(age), class FROM (SELECT * FROM test ORDER BY age DESC) T GROUP BY class
伊谢尔伦

反对@Ewellyuan 的答案,使用group的SQL select的列要么使用聚合函数,要么在group子句中。
在一些对sql严格的数据库(如oracle)中,违反此规则会直接报错。
写一个SQL供题主参考,SQL没测试

select test.* from test t1, (select max(age) a, class b from test group by b) t where t1.age=t.a and t1.class=t.b

不知道有没有更简单的方法

怪我咯

我来重写一下:

select t1.*
from test t1,
  (select class, max(age) as age from test group by class) t2
where t1.class = t2.class and t1.age = t2.age;

或者用inner join:

select t1.*
from test t1
join (select class, max(age) as age from test group by class) t2
on t1.class = t2.class and t1.age = t2.age;

这两条语句语义上是等价的。

使用left join的写法:

select t1.*
from test t1
left join test t2 on t1.class = t2.class and t1.age < t2.age
where t2.id is null;

具体请参见我就此写的一篇文章:
http://segmentfault.com/a/1190000004157112

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号