扫码关注官方订阅号
想请教下,这张表
自己用命令分组的话,结果却不正确了,
结果显示为qiu 42, (应该是liu 42),怎样这样显示出
自己写的只能显示一个类别里的,怎样能显示所有类别里的最大年龄?假如这样写的话 就是这样的截图了
ringa_lee
先排个序:
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
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
先排个序:
反对@Ewellyuan 的答案,使用group的SQL select的列要么使用聚合函数,要么在group子句中。
在一些对sql严格的数据库(如oracle)中,违反此规则会直接报错。
写一个SQL供题主参考,SQL没测试
不知道有没有更简单的方法
我来重写一下:
或者用inner join:
这两条语句语义上是等价的。
使用left join的写法:
具体请参见我就此写的一篇文章:
http://segmentfault.com/a/1190000004157112