时间:2021-07-01 10:21:17 帮助过:4人阅读
当然,我们也可以这么写:
SELECT * FROM ( SELECT * FROM t_class ORDER BY age DESC) AS b GROUP BY class;
但是,我不建议这么写,因为这么写有些不可预知的事情发生。我们先order by 再group by ,结果可能不是取的年龄最大的学生信息,具体原因,我还在寻找中,当然你知道原因也可以告诉我,证据如下:
所以,我们可以这么去写:
/**方法1:**/ SELECT * FROM t_class t WHERE t.age = (SELECT MAX(age) FROM t_class WHERE t.class = class) ORDER BY class; /**方法2:**/ SELECT t_class.id,t_class.name,t_class.age,t_class.class FROM t_class INNER JOIN (SELECT class,MAX(age) AS maxAge FROM t_class GROUP BY class)t ON (t.class = t_class.class AND t_class.age = t.maxAge);
至于那个方法的效率高,你可以自己测试一下!
可以读一下这篇文字,可以更好的理解group by:http://www.cnblogs.com/wiseblog/articles/4475936.html
http://blog.csdn.net/john_hongming/article/details/42742965
http://www.th7.cn/db/mysql/201502/91713.shtml
http://yueliangdao0608.blog.51cto.com/397025/81278
本文出自 “我的JAVA世界” 博客,请务必保留此出处http://hanchaohan.blog.51cto.com/2996417/1892304
mySQL之group By的简单分析
标签:mysql group by